Skip to content

Instantly share code, notes, and snippets.

@alfasin
Created December 16, 2017 09:11
Show Gist options
  • Save alfasin/2ccbd5af7a581d5974858502bcd22fb7 to your computer and use it in GitHub Desktop.
Save alfasin/2ccbd5af7a581d5974858502bcd22fb7 to your computer and use it in GitHub Desktop.
An example of how to benchmark js code. In this example we compare 3 ways to remove elements from an array.
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
// add tests
suite.add('shift', function() {
let arr = [1,2,3,4,5,6,7,8,9,0]
for (let i in arr) {
arr.shift()
}
})
.add('slice', function() {
let arr = [1,2,3,4,5,6,7,8,9,0]
for (let i in arr) {
arr.slice(1)
}
})
.add('pop', function() {
let arr = [1,2,3,4,5,6,7,8,9,0]
for (let i in arr) {
arr.pop()
}
})
// add listeners
.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