Last active
August 29, 2015 14:07
-
-
Save assaf/d07a39f32fcc697cb1a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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