https://github.com/bestiejs/benchmark.js
安装
npm i --save benchmark
官方例子
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
// add tests
suite
.add('RegExp#test', function () {
/o/.test('Hello World!');
})
.add('String#indexOf', function () {
'Hello World!'.indexOf('o') > -1;
})
// add listeners
.on('cycle', function (event) {
console.log('event', event)
console.log(String(event.target));
})
.on('complete', function () {
console.log('this', this)
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({'async': true});
// logs:
// => RegExp#test x 4,161,532 +-0.99% (59 cycles)
// => String#indexOf x 6,139,623 +-1.00% (131 cycles)
// => Fastest is String#indexOf
自己测个demo
果然还是数组快
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
function getStr() {
return Math.random().toString(36).slice(2)
}
let s1 = getStr()
let s2 = 'o' + getStr()
let s3 = 'on' + getStr()
let list = [
s1, s2, s3
]
// add tests
suite
.add('String#startsWith', function () {
list.map(
s => s.startsWith('on')
)
})
.add('Array#index', function () {
list.map(
s => s[0] === 'o' && s[1] === 'n'
)
})
// add listeners
.on('cycle', function (event) {
// console.log('event', event)
console.log(String(event.target));
})
.on('complete', function () {
// console.log('this', this)
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({'async': true});
// String#startsWith x 10,134,519 ops/sec ±0.33% (95 runs sampled)
// Array#index x 34,323,466 ops/sec ±0.31% (92 runs sampled)
// Fastest is Array#index
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/3188486