您的位置:首页 > Web前端 > JavaScript

js 使用benchmark 测试代码性能

2018-04-10 00:00 316 查看
https://github.com/bestiejs/benchmark.js

测试代码和输出

测试js中,字符串的查找函数效率,分别使用正则表达式,includes,indexOf三个进行测试,结果表明indexOf最快

其中,Ops/sec 测试结果以每秒钟执行测试代码的次数(Ops/sec)显示,这个数值越大越好。除了这个结果外,同时会显示测试过程中的统计误差,以及相对最好的慢了多少(%)

var Benchmark = require('benchmark');

var suite = new Benchmark.Suite;

// add tests
suite.add('RegExp#test', function () {
/o/.test('Hello World!');
}).add('includes#test', function () {
'Hello World!'.includes('o');
}).add('String#indexOf', function () {
'Hello World!'.indexOf('o') > -1;
})
// 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
.run({'async': true});

// logs:
// RegExp#test x 19,270,682 ops/sec ±1.39% (86 runs sampled)
// includes#test x 40,055,049 ops/sec ±0.64% (90 runs sampled)
// String#indexOf x 402,704,424 ops/sec ±2.44% (85 runs sampled)
// Fastest is String#indexOf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: