-
Notifications
You must be signed in to change notification settings - Fork 48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Possible alternative use of switch that might be fast enough #150
Comments
True, your code example (switch2) is even a tiny bit faster than the original if-then-else (control):
However, switch2 also yields the warnings import 'dart:math';
import 'package:benchmark/benchmark.dart';
import 'package:more/collection.dart';
import 'package:petitparser/petitparser.dart';
final random = Random(42);
const context = Context('', 0);
final input = IntegerRange(1024 * 1024)
.map<Result<String>>((_) => random.nextBool()
? context.success<String>('success', random.nextInt(0xffff))
: context.failure<String>('failure', random.nextInt(0xffff)))
.toList(growable: false);
Benchmark exercise(int Function(Result<String>) underTest) => () {
for (var i = 0; i < input.length; i++) {
underTest(input[i]);
}
};
void main() {
experiments(
control: exercise((result) => result.isSuccess ? result.position : -1),
experiments: {
'switch1': exercise((result) => switch (result) {
Success(position: final position) => position,
Failure() => -1,
}),
'switch2': exercise((result) => switch (result) {
final Success s => s.position,
Failure _ => -1,
}),
'switch3': exercise((result) => switch (result) {
final Success<String> s => s.position,
Failure<String> _ => -1,
}),
},
);
} |
The second case could be |
That makes it a bit faster, but not by much:
|
You rewrote this to be faster:
I wonder if this might have been fast enough to still use the switch:
I understand that might work faster for sorting out types and mapping them to branches. I think
Type()
goes through a lot of extra work compared toType _
.The text was updated successfully, but these errors were encountered: