Skip to content

Instantly share code, notes, and snippets.

@emilniklas
Last active August 29, 2015 14:27
Show Gist options
  • Save emilniklas/e8edf8de020a74315bf3 to your computer and use it in GitHub Desktop.
Save emilniklas/e8edf8de020a74315bf3 to your computer and use it in GitHub Desktop.
dart:mirrors benchmark
import 'dart:mirrors';
class Class {
int field;
}
final mirror = reflectClass(Class);
final constructor = const Symbol('');
main() {
testIterations(100, 'a hundred');
testIterations(1000, 'a thousand');
testIterations(10000, '10 thousand');
testIterations(20000, '20 thousand');
testIterations(50000, '50 thousand');
testIterations(100000, 'a hundred thousand');
testIterations(1000000, 'a million');
testIterations(2000000, 'two million');
testIterations(5000000, 'five million');
testIterations(10000000, 'ten million');
}
testIterations(int times, String description) {
final repeats = 50;
// Repeat 50 times
var durationsMirrors = 0;
for (var i in new List.filled(repeats, 1)) {
// Start times
var starttimeMirrors = new DateTime.now().millisecondsSinceEpoch;
// Run benchmark
testWithMirrors(times);
// Sum up the milliseconds each iteration of the test takes
durationsMirrors += new DateTime.now().millisecondsSinceEpoch - starttimeMirrors;
}
// Get the average milliseconds it took the complete the test
var durationMirrors = durationsMirrors / repeats;
// Do the same for the test without mirrors
var durationsWithoutMirrors = 0;
for (var i in new List.filled(repeats, 1)) {
var starttimeWithoutMirrors = new DateTime.now().millisecondsSinceEpoch;
testWithoutMirrors(times);
durationsWithoutMirrors += new DateTime.now().millisecondsSinceEpoch - starttimeWithoutMirrors;
}
var durationWithoutMirrors = durationsWithoutMirrors / repeats;
// Get how many times slower the mirrors implementation was
var slower = durationMirrors / durationWithoutMirrors;
print('''$description instantiations and assignments:
using mirrors: $durationMirrors ms
without using mirrors: $durationWithoutMirrors ms
${slower.toString() == 'Infinity'
? 'Without using mirrors was to quick to measure'
: 'Mirrors was $slower times slower.'}''');
}
testWithMirrors(int times) {
for (var i in new List<int>.filled(times, 1))
mirror.newInstance(constructor, []).setField(#field, i);
}
testWithoutMirrors(int times) {
for (var i in new List<int>.filled(times, 1))
new Class().field = i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment