Skip to content

Instantly share code, notes, and snippets.

@simg
Created July 26, 2017 14:36
Show Gist options
  • Save simg/606e80dd1eaef8f35f28f99641a7e70d to your computer and use it in GitHub Desktop.
Save simg/606e80dd1eaef8f35f28f99641a7e70d to your computer and use it in GitHub Desktop.
// run using: node --expose_gc loop_reduce_test.ts
// to allow for high precision timing
function arrayReduceTest(ary) {
return ary.reduce((acc, x) => {
return acc + x;
}, 0);
}
function arrayLoopTest(ary) {
var acc = 0, i;
for (i = 0; i < ary.length; i++) {
acc += ary[i];
}
return acc;
}
function runTest(length) {
var ary;
var tests = [
arrayReduceTest,
arrayLoopTest,
];
tests.map(function(fn){
ary = arrayCreate(length);
precisionTime(fn.name, function(){
fn(ary);
});
});
}
runTest(1000000);
/* util functions */
function arrayCreate(length) {
return Array(length).fill(1);
}
function precisionTime(testName, fn) {
global.gc();
var iStart = process.hrtime();
fn();
console.log(padEnd(testName, 20), padEnd(process.hrtime(iStart), 20), padEnd(process.memoryUsage().heapUsed.toLocaleString(), 20));
}
function padEnd(str, length) {
if (str.length >= length) {
return str;
} else {
return str + " ".repeat(length - str.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment