Created
March 13, 2013 13:32
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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