Skip to content

Instantly share code, notes, and snippets.

@munificent
Created October 29, 2014 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munificent/b8f2785c7d1744bdd22f to your computer and use it in GitHub Desktop.
Save munificent/b8f2785c7d1744bdd22f to your computer and use it in GitHub Desktop.
Getters versus fields
// On my laptop, I get:
// getter run 1: 73ms
// getter run 3: 64ms
// getter run 11: 63ms
// getter run 12: 14ms
// getter run 30: 13ms
// field run 1: 68ms
// field run 7: 64ms
// field run 9: 63ms
const NUM_TRIALS = 100;
const NUM_ITERATIONS = 1000000;
void main(List<String> args) {
run("field", () {
var objs = [];
for (var i = 0; i < NUM_ITERATIONS; i++) {
objs.add(new Field());
}
var sum = 0;
for (var obj in objs) {
sum += obj.a.length + obj.b.length + obj.c.length;
}
if (sum != NUM_ITERATIONS * 3) throw "!";
});
run("getter", () {
var objs = [];
for (var i = 0; i < NUM_ITERATIONS; i++) {
objs.add(new Getter());
}
var sum = 0;
for (var obj in objs) {
sum += obj.a.length + obj.b.length + obj.c.length;
}
if (sum != NUM_ITERATIONS * 3) throw "!";
});
}
abstract class Base {
int get a;
int get b;
int get c;
}
class Field implements Base {
final a = "a";
final b = "b";
final c = "c";
}
class Getter implements Base {
get a => "a";
get b => "b";
get c => "c";
}
void run(String label, callback()) {
var best = 99999999.0;
// Run the benchmark several times. This ensures the VM is warmed up and lets
// us see how much variance there is.
for (var i = 0; i <= NUM_TRIALS; i++) {
var start = new DateTime.now();
callback();
var elapsed = new DateTime.now().difference(start).inMilliseconds;
// Keep track of the best run so far.
if (elapsed >= best) continue;
best = elapsed;
// Don't print the first run. It's always terrible since the VM hasn't
// warmed up yet.
if (i == 0) continue;
print("$label run $i: ${elapsed}ms");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment