Skip to content

Instantly share code, notes, and snippets.

@schultek
Created July 11, 2024 10:03
Show Gist options
  • Save schultek/d4f8cc0d46873a6324dc106c6a288bd8 to your computer and use it in GitHub Desktop.
Save schultek/d4f8cc0d46873a6324dc106c6a288bd8 to your computer and use it in GitHub Desktop.
map performance benchmark
void main() {
bench('version 1', () {
get1();
});
bench('version 2', () {
get2();
});
}
Map<String, dynamic> get1() {
return {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
};
}
Map<String, dynamic> get2() {
final map = <String, dynamic>{};
map['a'] = 1;
map['b'] = 2;
map['c'] = 3;
map['d'] = 4;
return map;
}
void bench(String name, void Function() f,
{int times = 200000, bool sum = true}) {
for (var i = 0; i < times / 2; i++) {
f();
}
final s = Stopwatch()..start();
for (var i = 0; i < times; i++) {
f();
}
s.stop();
var time = formatTime(s.elapsedMicroseconds ~/ (sum ? 1 : times));
print("$name: $time");
}
String formatTime(int microseconds) {
if (microseconds < 5000) {
return '${microseconds}µs';
} else if (microseconds < 1000000) {
return '${microseconds / 1000}ms';
} else {
return '${microseconds / 1000000}s';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment