Last active
December 10, 2015 16:56
-
-
Save gaperton/f2e4551ebc0a74035dd5 to your computer and use it in GitHub Desktop.
Iteration through object hash
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 keys = [], | |
attrs = {}, | |
c = []; | |
for( var i = 0; i < 20; i++ ){ | |
keys.push( 'a' + i ); | |
attrs[ 'a' + i ] = i; | |
c.push( 'a.a' + i + '=== void 0 || f( a.a' + i + ');') | |
} | |
function Obj(){ | |
this.a1 = 0; | |
this.a2 = 0; | |
this.a3 = 0; | |
this.a4 = 0; | |
this.a5 = 0; | |
this.a6 = 0; | |
this.a7 = 0; | |
this.a8 = 0; | |
this.a9 = 0; | |
this.a10 = 0; | |
this.a11 = 0; | |
this.a12 = 0; | |
this.a13 = 0; | |
this.a14 = 0; | |
this.a15 = 0; | |
this.a16 = 0; | |
this.a17 = 0; | |
this.a18 = 0; | |
this.a19 = 0; | |
this.a20 = 0; | |
} | |
var objAttrs = new Obj(); | |
var compiled = new Function( 'a', 'f', c.join( '' ) ); | |
function testC(){ | |
var count = 0; | |
compiled( attrs, function( val ){ count+= val }); | |
} | |
function testLoop(){ | |
var count = 0; | |
for( var i = 0; i < keys.length; i++ ){ | |
var name = keys[ i ], | |
val = attrs[ name ]; | |
if( val !== void 0 ){ | |
count += val; | |
} | |
} | |
} | |
function testHash(){ | |
var count = 0; | |
for( var name in attrs ){ | |
count += attrs[ name ]; | |
} | |
} | |
function testObj(){ | |
var count = 0; | |
for( var name in objAttrs ){ | |
count += objAttrs[ name ]; | |
} | |
} | |
function measure( fun, count ){ | |
var start = window.performance.now(); | |
for( var i = 0; i < count; i++ ){ | |
fun(); | |
} | |
console.log( window.performance.now() - start ); | |
} | |
console.log( "Hash loop:" ); | |
measure( testHash, 1000000 ); | |
console.log( "Class loop:" ); | |
measure( testObj, 1000000 ); | |
console.log( "Array loop:" ); | |
measure( testLoop, 1000000 ); | |
console.log( "Unrolled loop:" ); | |
measure( testC, 1000000 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment