Last active
November 29, 2019 08:53
-
-
Save Aschen/6225c7bc9c67313f9eeb3571964984e5 to your computer and use it in GitHub Desktop.
Benchmarking creating array from array
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 suite = new Benchmark.Suite | |
const array = []; | |
for (let i = 0; i < 1000; i++) { | |
array.push({ value: i }); | |
} | |
suite | |
.add('foreach', () => { | |
let res = [] | |
array.forEach(item => { | |
res.push({ value: item.value * 2 }); | |
}); | |
}) | |
.add('for (const of)', () => { | |
let res = [] | |
for (const item of array) { | |
res.push({ value: item.value * 2 }); | |
} | |
}) | |
.add('for (let i)', () => { | |
let res = [] | |
for (let i = 0; i < array.length; ++i) { | |
const item = array[i]; | |
res.push({ value: item.value * 2 }); | |
} | |
}) | |
.add('map', () => { | |
let res = array.map(item => { | |
return { value: item.value * 2 } | |
}); | |
}) | |
.on('cycle', function(event) { | |
console.log(String(event.target)); | |
}) | |
.on('complete', function() { | |
console.log('Fastest is ' + this.filter('fastest').map('name')); | |
}) | |
.run(); |
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
$ node --version | |
v12.13.0 | |
$ node loop-create-array.js | |
foreach x 60,450 ops/sec ±8.91% (87 runs sampled) | |
for (const of) x 112,013 ops/sec ±1.97% (84 runs sampled) | |
for (let i) x 113,350 ops/sec ±2.63% (82 runs sampled) | |
map x 153,657 ops/sec ±4.45% (78 runs sampled) | |
Fastest is map |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment