Skip to content

Instantly share code, notes, and snippets.

@ejb
Created June 30, 2016 17:14
Show Gist options
  • Save ejb/2c615283474d84ebf171e81b5c79950d to your computer and use it in GitHub Desktop.
Save ejb/2c615283474d84ebf171e81b5c79950d to your computer and use it in GitHub Desktop.
Performance test: Loops versus array methods
// This script should be run with Node.js
var short = generateDummy(100);
var med = generateDummy(10000);
var long = generateDummy(1000000);
console.info('Big loop:');
test(short, bigLoop);
test(med, bigLoop);
test(long, bigLoop);
console.info('Array methods:');
test(short, arrayMethods);
test(med, bigLoop);
test(long, arrayMethods);
function test(data, fn) {
var hrstart = process.hrtime();
fn(data);
var hrend = process.hrtime(hrstart);
console.info(data.length+",%d", hrend[1]/1000000);
}
function generateDummy(length) {
var dummy = [];
for (var i = 0; i < length; i++) {
dummy.push({
seats: Math.round(Math.random() * 100),
visible: (Math.random() < 0.2)
});
}
return dummy;
}
function bigLoop(data) {
var seats = 0;
var processed = [];
var filtered = [];
for (var i = 0; i < data.length; i++) {
var d = data[i];
d.seatsPc = (d.seats / 320) * 100;
processed.push(d);
seats += d.seats;
if (d.visible === true) {
filtered.push(d);
}
}
}
function arrayMethods(data) {
// calculate percentages for each item
var processed = data.map(function(d,i) {
d.seatsPc = (d.seats / 320) * 100;
return d;
});
// count total seats
var seats = data.map(function(d,i) {
return d.seats;
}).reduce(function(prev,curr) {
return prev + curr;
});
// create new filtered array
var filtered = data.filter(function(d,i) {
return d.visible;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment