js使用benchmark进行函数基准测试(函数性能测试)

385 阅读1分钟

创建一个node项目

mkdir node-project-test
cd node-project-test
pnpm init -y
pnpm add benchmark @types/benchmark -D

新建测试方法

demo.test.js

import Benchmark from 'benchmark'

const suite = new Benchmark.Suite()

// add test
suite.add('正则表达式test方法', function () {
    /o/.test('Hello World!')
  })
    .add('字符串indexOf方法', function () {
      'Hello World!'.indexOf('o') > -1
    })
    // add listeners
    .on('cycle', function (event) {
      console.log(String(event.target))
    })
    .on('complete', function () {
      console.log('更快的方式为: ' + this.filter('fastest').map('name'))
    })
    // run async
    .run({ 'async': true })

执行测试方法

node ./demo.test.js

执行结果如下:

image.png