用benchmark测试es6的extends属性的性能
新建一个文件叫classExtend.js放以下代码:
'use strict';
const Benchmark = require('benchmark');
const benchmarks = require('beautify-benchmark');
const suite = new Benchmark.Suite();
class A {
calculate() {
return 1 * 1;
}
}
class B extends A {}
class C extends B {}
suite
.add('class A', function() {
const a = new A();
a.calculate();
})
.add('class B', function() {
const b = new B();
b.calculate();
})
.add('class C', function() {
const c = new C();
c.calculate();
})
.on('cycle', function(event) {// 每个测试跑完后,输出信息
benchmarks.add(event.target);
})
.on('start', function() {
console.log('\n node version: %s, date: %s\n Starting...', process.version, Date());
})
// 这里的 async 不是 mocha 测试那个 async 的意思,这个选项与它的时间计算有关,默认勾上就好了。
.on('complete', function done() {
benchmarks.log();
})
.run({ async: false });
由于需要用node环境所以有几步必要的操作:
1.在当前文件夹初始化npm,全部回车就行
npm init
2.安装代码中所需要的两个依赖:
cnpm i benchmark beautify-benchmark
3.用node命令直接运行这个js文件:
node classExtend
其中,Ops/sec 测试结果以每秒钟执行测试代码的次数(Ops/sec)显示,这个数值越大越好。除了这个结果外,同时会显示测试过程中的统计误差,以及相对最好的慢了多少(%)
结论:
es6的extends每继承一层它的性能都会有所下降,所以不推荐用es6的extends写太多的继承。