Skip to content

Instantly share code, notes, and snippets.

@spikegrobstein
Created July 30, 2011 01:49
Show Gist options
  • Save spikegrobstein/1115098 to your computer and use it in GitHub Desktop.
Save spikegrobstein/1115098 to your computer and use it in GitHub Desktop.
benchmarking static vs objects in JS
function build_static() {
var Frontrunner = (function(){
var FR = null;
var name = "spike";
return {
init: function() {
FR = this;
return this;
},
talk: function() {
this.speak();
},
speak: function() {
console.log('yo, ' + this.name());
},
me: function() {
return FR;
},
name: function() {
return name;
}
}
})().init();
return Frontrunner;
}
function build_object() {
var Frontrunner = function() {
var FR = this;
var name = "spike";
this.talk = function() {
this.speak();
};
this.speak = function() {
console.log('yo, ' + this.name());
};
this.me = function() {
return FR;
};
this.name = function() {
return name;
}
}
return new Frontrunner();
}
function benchmark(func, iterations) {
var d1 = new Date();
var i = 0;
var a = []; // where we keep everything
for (i = 0; i < iterations; ++i) {
a.shift(func());
}
var d2 = new Date();
return (d2 - d1) / 1000;
}
var iterations = 100000; // number of iterations to run the function
var count = 5; // number of times to run the benchmark
// benchmarks
var static_bms = [];
var object_bms = [];
var static_total = 0;
var object_total = 0;
var i = 0;
for (i = 0; i < count; ++i) {
static_bms.unshift(benchmark(build_static, iterations));
object_bms.unshift(benchmark(build_object, iterations));
static_total += static_bms[0];
object_total += object_bms[0];
}
// now, let's average
var static_average = static_total / static_bms.length;
var object_average = object_total / object_bms.length;
console.log('static average: ' + static_average);
console.log('object average: ' + object_average);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment