benchmarkjs 测试函数性能
安装
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"));
console.log("name is ", this.map("name"));
console.log("mean is ", this.map("stats").map(x => x.mean));
// console.log("times is ", this.map("times"));
})
// run async
.run({"async": true});
// String#startsWith x 10,141,354 ops/sec ±1.20% (90 runs sampled)
// Array#index x 32,883,950 ops/sec ±0.98% (91 runs sampled)
// Fastest is [ "Array#index" ]
// name is [ "String#startsWith", "Array#index" ]
// mean is [ 9.860616140762061e-8, 3.04099715762954e-8 ]