Skip to content

Instantly share code, notes, and snippets.

@tj
Created August 24, 2010 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tj/547641 to your computer and use it in GitHub Desktop.
Save tj/547641 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);
},
'Constructor': function(){
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:
4445ms
- Constructor:
24ms
@creationix
Copy link

I wonder how much of the overhead is my custom logic (look for initialize, seal, etc) and how much is Object.create(Prototype) vs new Constructor()

@tj
Copy link
Author

tj commented Aug 24, 2010

didnt try that, took out seal and it seemed quite a bit faster, probably still slower since its a user-land fn call but would be nice to know

@creationix
Copy link

Turns out seal is the biggest cost here. See my fork http://gist.github.com/547752

@tj
Copy link
Author

tj commented Aug 24, 2010

ya lots of overhead with the iteration / descriptor changes i guess

@creationix
Copy link

Well I can live without seal if it's going to cost that much. Or I can use it in development and disable it on deployment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment