benchmarkjs 测试函数性能

三世轮回 提交于 2020-03-05 12:39:42

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!