Skip to content

Instantly share code, notes, and snippets.

@yamad
Last active September 16, 2020 00:25
Show Gist options
  • Save yamad/0fb920f99ca5e769e42c0c0580b65226 to your computer and use it in GitHub Desktop.
Save yamad/0fb920f99ca5e769e42c0c0580b65226 to your computer and use it in GitHub Desktop.
Benchmarking javascript loop performance
Install `benchmark` (https://benchmarkjs.com/) and run:
npm install --save benchmark
node loopperf.js
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