Skip to content

Instantly share code, notes, and snippets.

@lrhn
Last active February 19, 2021 23:25
Show Gist options
  • Save lrhn/706ec53a39f57f4fc0133b32d9289c1b to your computer and use it in GitHub Desktop.
Save lrhn/706ec53a39f57f4fc0133b32d9289c1b to your computer and use it in GitHub Desktop.
Comparison of List.[] and List.elementAt.
main() async {
var list = [for (var i = 0; i < 10000; i++) i.isEven ? i : -i];
for (var i = 0; i < 5; i++) {
print("elementAt : ${bench1(list)}/ms");
await Future((){}); // Don't block browser.
print("operator[]: ${bench2(list)}/ms");
await Future((){});
}
}
double bench1(List<int> list) {
var c = 0, e = 0;
var result = 0;
var sw = Stopwatch()..start();
do {
for (int i = 0; i < list.length; i++) {
result += list.elementAt(i);
}
c += 1;
e = sw.elapsedMilliseconds;
} while (e < 2000);
if (result == 0) throw "whoops";
return (c * list.length)/e;
}
double bench2(List<int> list) {
var c = 0, e = 0;
var result = 0;
var sw = Stopwatch()..start();
do {
for (int i = 0; i < list.length; i++) {
result += list[i];
}
c += 1;
e = sw.elapsedMilliseconds;
} while (e < 2000);
if (result == 0) throw "whoops";
return (c * list.length)/e;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment