Created
April 26, 2018 03:01
-
-
Save liqiang372/608467da6ac0fae7744c4dd38c026692 to your computer and use it in GitHub Desktop.
comparison of lazy evaluation
This file contains hidden or 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
const _ = require('lodash'); | |
const t = require('transducers.js'); | |
const arrayofRandoms = randomCeil => length => | |
Array.from({length: length}, (v, i) => | |
Math.floor(Math.random() * randomCeil)); | |
const arrOfMillion = arrayofRandoms(100)(1e6); | |
const tripleIt = (el) => el * 3; | |
const isEven = (el) => el % 2 === 0; | |
const timeIt = (name, fn) => { | |
console.time(name); | |
fn(); | |
console.timeEnd(name); | |
} | |
/** | |
* Native methods | |
*/ | |
timeIt('million - native', () => { | |
arrOfMillion | |
.map(tripleIt) | |
.filter(isEven) | |
}) | |
timeIt('million - native x 2', () => { | |
arrOfMillion | |
.map(tripleIt) | |
.map(tripleIt) | |
.filter(isEven) | |
}) | |
timeIt('million - native x 4', () => { | |
arrOfMillion | |
.map(tripleIt) | |
.map(tripleIt) | |
.map(tripleIt) | |
.map(tripleIt) | |
.filter(isEven) | |
}) | |
/** | |
* Lodash version | |
*/ | |
timeIt('million - lodash', () => { | |
_(arrOfMillion) | |
.map(tripleIt) | |
.filter(isEven) | |
.value() | |
}) | |
timeIt('million - lodash x 2', () => { | |
_(arrOfMillion) | |
.map(tripleIt) | |
.map(tripleIt) | |
.filter(isEven) | |
.value() | |
}) | |
timeIt('million - lodash x 4', () => { | |
_(arrOfMillion) | |
.map(tripleIt) | |
.map(tripleIt) | |
.map(tripleIt) | |
.map(tripleIt) | |
.filter(isEven) | |
.value() | |
}) | |
/** | |
* transducers | |
*/ | |
timeIt('million - transducers', () => { | |
t.seq( | |
arrOfMillion, | |
t.compose( | |
t.filter(isEven), | |
t.map(tripleIt) | |
) | |
) | |
}) | |
timeIt('million - transducers x 2', () => { | |
t.seq( | |
arrOfMillion, | |
t.compose( | |
t.filter(isEven), | |
t.map(tripleIt), | |
t.map(tripleIt) | |
) | |
) | |
}) | |
timeIt('million - transducers x 4', () => { | |
t.seq( | |
arrOfMillion, | |
t.compose( | |
t.filter(isEven), | |
t.map(tripleIt), | |
t.map(tripleIt), | |
t.map(tripleIt), | |
t.map(tripleIt) | |
) | |
) | |
}) | |
// million - native: 210.871ms | |
// million - native x 2: 302.492ms | |
// million - native x 4: 492.038ms | |
// million - lodash: 41.545ms | |
// million - lodash x 2: 45.860ms | |
// million - lodash x 4: 52.093ms | |
// million - transducers: 123.363ms | |
// million - transducers x 2: 131.208ms | |
// million - transducers x 4: 134.362ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment