Created
October 8, 2010 14:13
-
-
Save bga/616859 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
es5 introduces new Object api. Object.keys returns array of own enumerable keys of object. | |
In es3 we have classic construction "for in hasOwnProperty" for this purposes. | |
Test try to find what is best - es3 enumeration or es5 | |
In es5 we have overhead of array making and allocation | |
In es3 we have overhead of enumeration extra properties from prototype chain and filter it(using hasOwnProperty - extra function call) | |
update 1 | |
according brilliant idea of @abozhilov (http://twitter.com/abozhilov/status/26758011447) there is 3rd way which | |
uses nonstandard __proto__ (presents in v8 and JagerMonkey) | |
*/ | |
var m = 10; | |
var prefix = ''; | |
var _fill = function(a, len) | |
{ | |
var i = len; while(i--) | |
a[prefix + i] = 0; | |
return a; | |
}; | |
var aL = _fill({}, m); | |
_speedTest( | |
[ | |
function(n) | |
{ | |
var a = aL; | |
var i = n; while(i--) | |
{ | |
for(var j in a) | |
{ | |
if(a.hasOwnProperty(j)) | |
++a[j]; | |
} | |
} | |
}, | |
function(n) | |
{ | |
var a = aL; | |
var i = n; while(i--) | |
{ | |
var keys = Object.keys(a); | |
var j = keys.length; while(j--) | |
{ | |
++a[keys[j]]; | |
} | |
} | |
}, | |
function(n) | |
{ | |
var a = aL; | |
var i = n; while(i--) | |
{ | |
var proto = a.__proto__; | |
a.__proto__ = null; | |
for(var j in a) | |
{ | |
++a[j]; | |
} | |
a.__proto__ = proto; | |
} | |
} | |
], | |
100000 | |
); | |
/* | |
chrome7 100000 | |
m = 10 prefix = '' | |
0: 1210 ms | |
1: 615 ms | |
2: 936 ms | |
m = 10 prefix = 'xxx' | |
0: 1315 ms | |
1: 837 ms | |
2: 1327 ms | |
ff4b3 100000 | |
m = 10 prefix = 'xxx' | |
0: 1130 ms | |
1: 1522 ms | |
2: 496 ms | |
m = 10 prefix = '' | |
0: 1215 ms | |
1: 1375 ms | |
2: 523 ms | |
*/ | |
/* | |
Conclusion | |
1) in v8 es5 way is best, in JagerMonkey es3 is best, other engines hasnt Object.keys | |
2) v8 have optimization by numeric property names (see difference between cases with prefix = 'xxx' and prefix = '') | |
update 1 | |
__proto__ method in JagerMonkey is best | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment