Skip to content

Instantly share code, notes, and snippets.

@joelibaceta
Last active June 28, 2020 03:14
Show Gist options
  • Save joelibaceta/058e0ef27b868cec43a8f2fc8e830f92 to your computer and use it in GitHub Desktop.
Save joelibaceta/058e0ef27b868cec43a8f2fc8e830f92 to your computer and use it in GitHub Desktop.
For, ForEach ForOf Benchmark
"use strict";
var Benchmark = require('benchmark'); // Using https://benchmarkjs.com
const dogs = Array(1000000).fill("Doggy"); // One million of items
var suite = new Benchmark.Suite;
suite.add('for#test', function() {
for(let i = 0; i < dogs.lenght; i++){
return dog[i]
}
})
.add('for_caching#test', function() {
const size = dogs.lenght;
for(let i = 0; i < size; i++){
return dog[i]
}
})
.add('forEach#test', function() {
dogs.forEach(function(dog, i){
return dog;
});
})
.add('forof#test', function() {
for(const dog of dogs.entries()){
return dog;
}
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
suite.run({ 'async': true });
Fastest is for_caching#test
for#test x 55,659,660 ops/sec ±2.94% (78 runs sampled)
for_caching#test x 56,174,776 ops/sec ±3.19% (79 runs sampled)
forEach#test x 7,783,568 ops/sec ±4.54% (76 runs sampled)
forof#test x 5,088,843 ops/sec ±4.21% (79 runs sampled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment