Created
December 17, 2020 09:55
-
-
Save geeknees/3492c895afd2c3a0dc45ccee69b8d42a to your computer and use it in GitHub Desktop.
eachSlice bench
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
Test start! | |
chunkWhile x 2,882,663 ops/sec ±0.71% (86 runs sampled) | |
chunkRec x 2,601,506 ops/sec ±0.91% (86 runs sampled) | |
chunkReduce x 2,993,484 ops/sec ±0.89% (85 runs sampled) | |
Fastest is chunkReduce |
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
const Benchmark = require('benchmark') | |
const chunkWhile = (array, size = 2) => { | |
const result = [] | |
const tmp = [...array] | |
while (tmp.length) { | |
result.push(tmp.splice(0, size)) | |
} | |
return result | |
} | |
const chunkRec = (array, size = 2, result = []) => { | |
if (array.length === 0) { | |
return result | |
} | |
result.push(array.splice(0, size)) | |
return chunkRec(array, size, result) | |
} | |
const chunkReduce = (array, size = 2) => { | |
return array.reduce( | |
(result, _, i) => (i % size ? result : [...result, array.slice(i, i + size)]), | |
[] | |
) | |
} | |
const suite = new Benchmark.Suite | |
suite.on('start', () => { | |
console.log('Test start!') | |
}).add('chunkWhile', () => { | |
chunkWhile([1, 2, 3, 4, 5, 6], 2) | |
}).add('chunkRec', () => { | |
chunkRec([1, 2, 3, 4, 5, 6], 2) | |
}).add('chunkReduce', () => { | |
chunkReduce([1, 2, 3, 4, 5, 6], 2) | |
}).on('cycle', (event) => { | |
console.log(String(event.target)) | |
}).on('complete', function () { | |
console.log(`Fastest is ${this.filter('fastest').map('name')}`) | |
}).run({ async: true }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment