Created
November 21, 2010 15:46
-
-
Save founddrama/708829 to your computer and use it in GitHub Desktop.
A few different ways to make Arrays; which one gets the best performance?
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
jsc make-some-arrays.js | |
test #6: | |
total time: 0.405 seconds | |
test #7: | |
total time: 0.892 seconds |
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
function makeSomeArrays(){ | |
var outputter = function(fn){ | |
var ts = new Date().getTime(); | |
fn(); | |
var te = new Date().getTime(); | |
console.log("total time: " + (te-ts)/1000 + | |
" seconds"); | |
}; | |
// 1 million: | |
var L = 1000000; | |
// use Array constructor; push L new arrays... | |
var test1 = function(){ | |
var a = new Array(); | |
for (var i=0; i<l ; i++) { | |
a.push(new Array()); | |
} | |
}; | |
// same as above - but in each case, | |
// declare a length to the array | |
var test2 = function(){ | |
var a = new Array(L); | |
for (var i=0; i<L; i++) { | |
a.push(new Array(0)); | |
} | |
}; | |
// same as above but via index assignment | |
var test3 = function(){ | |
var a = new Array(L); | |
for (var i=0; i<L; i++) { | |
a[i] = new Array(0); | |
} | |
}; | |
// for 4-6: replace Array constructor w/ Array literal | |
// notation except where declaring a length | |
// (container array, 5 + 6) | |
var test4 = function(){ | |
var a = []; | |
for (var i=0; i<L; i++) { | |
a.push([]); | |
} | |
}; | |
var test5 = function(){ | |
var a = new Array(L); | |
for (var i=0; i<L; i++) { | |
a.push([]); | |
} | |
}; | |
var test6 = function(){ | |
var a = new Array(L); | |
for (var i=0; i<L; i++) { | |
a[i] = []; | |
} | |
}; | |
var tests = [test1, test2, test3, test4, test5, test6]; | |
for (var j=0; j<tests.length; j++) { | |
console.info("test #" + (j+1) + ":"); | |
outputter(tests[j]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment