Skip to content

Instantly share code, notes, and snippets.

@SomeKittens

SomeKittens/aResults.md

Last active Sep 18, 2015
Embed
What would you like to do?
JavaScript Array.prototype vs for loops
[randallkoutnik:~/Dropbox/node/perf]$ node index.js
--- .forEach ---
.forEach took 26.271 ms
for loop took 2.369 ms
--- filter ---
.filter took 6.790 ms
for loop took 4.008 ms
'use strict';
var now = require("performance-now");
var _ = require('underscore');
module.exports = function (datums) {
console.log('--- filter ---');
var datumsFilter = datums.slice(0);
var startFilter = now();
var resultFilter = datumsFilter.filter(function (datum) {
return datum.num > 0.5;
});
var endFilter = now();
console.log('.filter took', (endFilter - startFilter).toFixed(3), 'ms');
var datumsLoop = datums.slice(0);
var startLoop = now();
var resultLoop = [];
for (var i = 0; i < datumsLoop.length; i++) {
if (datumsLoop[i].num > 0.5) {
resultLoop.push(datumsLoop[i]);
}
}
var endLoop = now();
console.log('for loop took', (endLoop - startLoop).toFixed(3), 'ms');
var datumsUnderscore = datums.slice(0);
var startUnderscore = now();
var resultUnderscore = _.filter(datumsUnderscore, function (datum) {
return datum.num > 0.5;
});
var endUnderscore = now();
console.log('underscore took', (endUnderscore - startUnderscore).toFixed(3), 'ms');
}
'use strict';
var now = require("performance-now");
var _ = require('underscore');
module.exports = function (datums) {
console.log('--- .forEach ---');
var datumsForEach = datums.slice(0);
var startForEach = now();
datumsForEach.forEach(function (datum) {
datum.firstName = 'Some';
});
var endForEach = now();
console.log('.forEach took', (endForEach - startForEach).toFixed(3), 'ms');
var datumsLoop = datums.slice(0);
var startLoop = now();
var resultLoop = [];
for (var i = 0; i < datumsLoop.length; i++) {
datumsLoop[i].firstname = 'Some';
}
var endLoop = now();
console.log('for loop took', (endLoop - startLoop).toFixed(3), 'ms');
var datumsUnderscore = datums.slice(0);
var startUnderscore = now();
var resultUnderscore = _.each(datumsUnderscore, function (datum) {
return datum.num > 0.5;
});
var endUnderscore = now();
console.log('underscore took', (endUnderscore - startUnderscore).toFixed(3), 'ms');
}
'use strict';
var forEach = require('./forEach');
var filter = require('./filter');
function genData (numItems) {
var datums = [];
for (var i = 0; i < numItems; i++) {
datums.push({
id: i,
num: Math.random(),
name: 'Kittens'
});
}
return datums;
}
var numToGen = process.env.NUM_ITEMS || 100000;
forEach(genData(numToGen));
filter(genData(numToGen));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment