Last active
September 16, 2020 00:25
-
-
Save yamad/0fb920f99ca5e769e42c0c0580b65226 to your computer and use it in GitHub Desktop.
Benchmarking javascript loop performance
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
Install `benchmark` (https://benchmarkjs.com/) and run: | |
npm install --save benchmark | |
node loopperf.js |
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(); | |
let array = Array(10000).fill(undefined).map((_, i) => i); | |
suite.add("for loop: i < array.length", | |
function() { | |
for (let i = 0; i < array.length; i++) | |
array[i]; | |
}) | |
.add("for loop: i < presaved length", | |
function() { | |
var count = array.length; | |
for (let i = 0; i < count; i++) { | |
array[i]; | |
} | |
}) | |
.add("for loop: i < inline length (Zakas HPJS)", | |
function() { | |
for (let i = 0, count = array.length; i < count; i++) { | |
array[i]; | |
} | |
}) | |
.add("for loop: reversed (Zakas HPJS)", | |
function() { | |
for (let i = array.length; i--; ) | |
array[i]; | |
}) | |
.add("forEach", | |
function() { | |
array.forEach(elt => elt); | |
}) | |
.add("map", | |
function() { | |
array.map(elt => elt); | |
}) | |
.on("cycle", function(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