Created
January 14, 2011 02:13
-
-
Save redspider/779041 to your computer and use it in GitHub Desktop.
Performance test for object creation
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
/** | |
* Performance test for object creation | |
* | |
* See: http://javascriptweblog.wordpress.com/2010/03/16/five-ways-to-create-objects/ | |
*/ | |
// 4. Simple constructor for new | |
var TInScope = function () { | |
this.test_prop = "4. Simple constructor for new"; | |
this.to_string = function () { | |
return this.test_prop; | |
} | |
}; | |
// 5. Prototype with Constructor for new | |
var TPrototype = function () { | |
this.test_prop = "5. Prototype with Constructor for new"; | |
}; | |
TPrototype.prototype.to_string = function () { | |
return this.test_prop; | |
}; | |
// 3. Constructor using object literal | |
var TDict = function () { | |
var that = {}; | |
that.test_prop = "3. Constructor using object literal"; | |
that.to_string = function () { | |
return this.test_prop; | |
} | |
return that; | |
} | |
/* Example output: | |
$ node ./perf1.js | |
4. Simple constructor for new : 732 ms | |
5. Prototype with Constructor for new : 343 ms | |
3. Constructor using object literal : 1154 ms | |
*/ | |
function do_test(test_obj) { | |
var start = new Date(); | |
var objs = []; | |
for (var i=0; i<1000000; i++) { | |
objs.push(new test_obj()); | |
} | |
var end = new Date(); | |
console.log((new test_obj().to_string()),":", end-start,"ms"); | |
} | |
do_test(TInScope); | |
do_test(TPrototype); | |
do_test(TDict); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment