Skip to content

Instantly share code, notes, and snippets.

@msh9
Created October 13, 2015 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msh9/079344cc5f4f412cca1a to your computer and use it in GitHub Desktop.
Save msh9/079344cc5f4f412cca1a to your computer and use it in GitHub Desktop.
Testing performance of difference ways of appending to a new array.
'use strict';
var iterations = 1000000,
outerIterations = 100;
function runit() {
var ary
,result
,idx;
ary = createData();
console.log('Executing while loop with prefix incre in test condition');
result = executeOuterLoop(pushForLoop, ary);
printResult(result);
console.log('Concatenating using concat');
result = executeOuterLoop(concat, ary);
printResult(result);
console.log('Concatenating using push with the forEach function');
result = executeOuterLoop(forEachFunc, ary);
printResult(result);
}
function executeOuterLoop(loopFunc, ary) {
var idx,
sum = [0, 0],
result;
for (idx = 0; idx < outerIterations; idx++) {
result = loopFunc(ary.slice(0));
sum[0] += result[0];
sum[1] += result[1];
}
sum[0] = sum[0] / outerIterations;
sum[1] = sum[1] / outerIterations;
return sum;
}
function printResult(diff) {
console.log('Loop time was %d seconds and %d milliseconds', diff[0], diff[1] / 1000000);
}
function createData() {
var idx
,retVal = [];
for (idx = 0 ; idx < iterations; idx++) {
retVal.push(Math.floor((Math.random() * 10) + 1));
}
return retVal;
}
function pushForLoop(ary) {
var start
,diff
,idx
,addTo = [];
start = process.hrtime();
for (idx = 0; idx < ary.length; idx++) {
addTo.push(ary[idx]);
}
diff = process.hrtime(start);
return diff;
}
function concat(ary) {
var start
,diff
,idx
,addTo = [];
start = process.hrtime();
addTo.concat(ary);
diff = process.hrtime(start);
return diff;
}
function forEachFunc(ary) {
var start
,diff
,idx
,addTo = [];
start = process.hrtime();
idx = -1;
ary.forEach(function (val) {
addTo.push(val);
});
diff = process.hrtime(start);
return diff;
}
runit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment