Created
August 24, 2010 14:28
-
-
Save tj/547641 to your computer and use it in GitHub Desktop.
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
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); | |
} |
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
Running 500000 times: | |
- Pattern: | |
4445ms | |
- Constructor: | |
24ms |
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
Turns out seal is the biggest cost here. See my fork http://gist.github.com/547752
ya lots of overhead with the iteration / descriptor changes i guess
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
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()