Skip to content

Instantly share code, notes, and snippets.

@creationix
Forked from tj/benchmark.js
Created August 24, 2010 15:37
Show Gist options
  • Save creationix/547752 to your computer and use it in GitHub Desktop.
Save creationix/547752 to your computer and use it in GitHub Desktop.
var Pattern = Object.create(Object.prototype, {
// Implement extend for easy prototypal inheritance
extend: {value: function extend(obj) {
if (obj === undefined) return Object.create(this);
obj.__proto__ = this;
Object.freeze(obj); // Lock the prototype to enforce no changes
return obj;
}},
// Implement new for easy self-initializing objects
new: {value: function new_() {
var obj = Object.create(this);
if (typeof obj.initialize !== 'function') return obj;
obj.initialize.apply(obj, arguments);
Object.seal(obj); // Lock the object down so the fields are static
return obj;
}}
});
var Vector = Pattern.extend({
initialize: function(x, y){
this.x = x;
this.y = y;
}
});
function Vector3(x, y) {
this.x = x;
this.y = y;
}
var compare = {
'Pattern': function(){
Vector.new(10, 50);
},
'Create': function(){
Object.create(Vector);
},
'CreateInitialize': function(){
Object.create(Vector).initialize(10, 50);
},
'Constructor': function(){
new Vector3(10, 50);
},
'SealedConstructor': function(){
Object.seal(new Vector3(10, 50));
}
}
var times = 500000;
console.log('Running %s times:', times);
for (var key in compare) {
var fn = compare[key];
console.log(' - %s:', key);
var start = Date.now();
var n = times;
while (n--) fn();
var end = Date.now();
console.log(' %sms', end - start);
}
Running 500000 times:
- Pattern:
3963ms
- Create:
145ms
- CreateInitialize:
674ms
- Constructor:
23ms
- SealedConstructor:
2550ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment