Instantly share code, notes, and snippets.

Embed
What would you like to do?
var Immutable = require("immutable"),
t = require("transducers-js"),
comp = t.comp,
map = t.map,
filter = t.filter,
transduce = t.transduce;
var inc = function(n) { return n + 1; };
var isEven = function(n) { return n % 2 == 0; };
var sum = function(a,b) { return a+b; };
// faster with transducers
var xf = comp(map(inc),filter(isEven));
var largeVector = Immutable.Vector();
var largeArray = [];
for(var i = 0; i < 10000000; i++) {
largeVector = largeVector.push(i);
largeArray.push(i);
}
console.time('Array map -> filter -> reduce');
largeArray.map(inc).filter(isEven).reduce(sum);
console.timeEnd('Array map -> filter -> reduce');
console.time('Array using Transducers');
transduce(xf, sum, 0, largeArray);
console.timeEnd('Array using Transducers');
console.time('Immutable.js vector map -> filter -> reduce');
largeVector.map(inc).filter(isEven).reduce(sum);
console.timeEnd('Immutable.js vector map -> filter -> reduce');
console.time('Immutable.js using Transducers');
transduce(xf, sum, 0, largeVector);
console.timeEnd('Immutable.js using Transducers');
console.time('Array reduce');
largeArray.reduce(function(sum, item) {
const plus1 = item + 1;
return (plus1 % 2 === 0) ? sum + plus1 : sum;
}, 0);
console.timeEnd('Array reduce');
console.time('Naive for loop');
var sum = 0;
for(var i = 0; i < largeArray.length; i++) {
var plus1 = largeArray[i] + 1;
if (plus1 % 2 === 0)
sum = sum + plus1;
}
console.timeEnd('Naive for loop');
@assaf

This comment has been minimized.

Owner

assaf commented Oct 13, 2014

Array map -> filter -> reduce: 2037ms
Array using Transducers: 489ms
Immutable.js vector map -> filter -> reduce: 712ms
Immutable.js using Transducers: 759ms
Array reduce: 512ms
Naive for loop: 19ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment