Skip to content

Instantly share code, notes, and snippets.

@Aschen
Last active November 29, 2019 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aschen/6225c7bc9c67313f9eeb3571964984e5 to your computer and use it in GitHub Desktop.
Save Aschen/6225c7bc9c67313f9eeb3571964984e5 to your computer and use it in GitHub Desktop.
Benchmarking creating array from array
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();
$ 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