Last active
November 29, 2019 08:53
-
-
Save Aschen/bf4179b78f2be7fceae446419a442169 to your computer and use it in GitHub Desktop.
Benchmarking append values to arrays
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 Benchmark = require('benchmark') | |
| const suite = new Benchmark.Suite | |
| const array = []; | |
| for (let i = 0; i < 1000; i++) { | |
| array.push({ value: i }); | |
| } | |
| suite | |
| .add('foreach & push', () => { | |
| let res = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }] | |
| array.forEach(item => { | |
| res.push({ value: item.value * 2 }); | |
| }); | |
| }) | |
| .add('for (const of) & push', () => { | |
| let res = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }] | |
| for (const item of array) { | |
| res.push({ value: item.value * 2 }); | |
| } | |
| }) | |
| .add('for (let i) & push', () => { | |
| let res = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }] | |
| for (let i = 0; i < array.length; ++i) { | |
| const item = array[i]; | |
| res.push({ value: item.value * 2 }); | |
| } | |
| }) | |
| .add('map & concat', () => { | |
| let res = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }] | |
| let res2 = array.map(item => { | |
| return { value: item.value * 2 } | |
| }); | |
| res = res.concat(res2) | |
| }) | |
| .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 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
| $ node --version | |
| v12.13.0 | |
| $ node loop-append-array.js | |
| foreach & push x 105,624 ops/sec ±2.96% (86 runs sampled) | |
| for (const of) & push x 112,869 ops/sec ±1.38% (87 runs sampled) | |
| for (let i) & push x 110,137 ops/sec ±1.68% (86 runs sampled) | |
| map & concat x 137,630 ops/sec ±1.49% (81 runs sampled) | |
| Fastest is map & concat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment