Skip to content

Instantly share code, notes, and snippets.

@nilclass
Created March 13, 2013 13:32
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 nilclass/5152051 to your computer and use it in GitHub Desktop.
Save nilclass/5152051 to your computer and use it in GitHub Desktop.
This script compares the performance of constructing an object with a bunch of methods from within a function and returning it, versus using a constructor with a prototype and the 'new' keyword.
//
// This script compares the performance of constructing an object
// with a bunch of methods from within a function and returning it,
// versus using a constructor with a prototype and the 'new' keyword.
//
// My results:
//
// node, v0.8.9:
// N = 1000000
// simple constructor 605ms
// real constructor 34ms
//
// Chromium
// N = 1000000
// simple constructor 555ms
// real constructor 22ms
var N = 1000000;
console.log('N = ' + N);
function bench(name, block) {
var start = new Date();
for(var i=0;i<N;i++) {
block();
}
var end = new Date();
var time = end.getTime() - start.getTime()
while(name.length < 20) {
name += ' ';
}
console.log(name + ' ' + time + 'ms');
}
var simpleConstructor = function() {
return {
a: function() {},
b: function() {},
c: function() {},
d: function() {},
e: function() {},
f: function() {},
g: function() {},
h: function() {},
i: function() {},
j: function() {},
k: function() {},
l: function() {},
m: function() {},
n: function() {},
o: function() {},
p: function() {},
q: function() {},
r: function() {},
s: function() {},
t: function() {}
}
};
var RealConstructor = function() {};
RealConstructor.prototype = {
a: function() {},
b: function() {},
c: function() {},
d: function() {},
e: function() {},
f: function() {},
g: function() {},
h: function() {},
i: function() {},
j: function() {},
k: function() {},
l: function() {},
m: function() {},
n: function() {},
o: function() {},
p: function() {},
q: function() {},
r: function() {},
s: function() {},
t: function() {}
};
bench('simple constructor', function() {
simpleConstructor();
});
bench('real constructor', function() {
new RealConstructor();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment