好的,我读过的基本内容:ES6类只是糖语法。好的,我想在性能级别上查看它。我创建了一个脚本,我在一个增加内部计数器的对象上迭代n次。
我尝试了不同的方法,使用new
语法,普通对象,Object.create
语法和...... ES6 class
语法。
我已经在节点上执行了我的脚本,在windows上执行了v4,在linux mint上执行了v5和v6。每次结果都相同:
现在问题:我的测试是否相关?我在语法观点上做错了吗?或ES6课程真的很慢?
感谢您的帮助!
编辑:我没有对此代码使用任何转换器,只是执行节点myFile.js来执行此测试
编辑:这是节点6.2.2上的执行结果
closureAlgo : 894ms
closureFunctionAlgo : 400ms
plainObjectAlgo : 861ms
plainObjectCreateAlgo : 336ms
objectAlgo : 335ms
classAlgo : 2684ms
以下是测试代码:
'use strict';
// easier to read this big number !
const iterations = Math.pow(10, 8);
let i;
function perfNode (cb) {
var begin = process.hrtime();
cb();
var diff = process.hrtime(begin);
console.log(arguments[0].name + ' : ' +Math.round((diff[0]*1000) + (diff[1]/1000000)) + "ms");
}
function perfWeb (cb) {
var begin = performance.now();
cb();
var end = performance.now();
console.log(Math.round((end - begin)) + "ms");
}
const perf = typeof performance !== 'undefined' ? perfWeb : perfNode;
function closureAlgo() {
function calc () {
var count = 0;
return {
increment : function () {
count++;
}
}
}
var calcImpl = calc();
for(i= 0; i < iterations; i++) {
calcImpl.increment();
}
}
function closureFunctionAlgo() {
function calc () {
var count = 0;
return {
increment : function () {
count++;
}
}
}
var calcImpl = Object.create(calc());
for(i= 0; i < iterations; i++) {
calcImpl.increment();
}
}
function plainObjectAlgo() {
var calc = {
count: 0,
increment: function () {
this.count++;
}
};
for(i= 0; i < iterations; i++) {
calc.increment();
}
}
function plainObjectCreateAlgo() {
var calc = {
count: 0,
increment: function () {
this.count++;
}
};
var calcImpl = Object.create(calc);
for(i= 0; i < iterations; i++) {
calcImpl.increment();
}
}
function objectAlgo() {
function Calc () {
this.count = 0;
}
Calc.prototype.increment = function () {
this.count++;
}
var calcImpl = new Calc();
for(i= 0; i < iterations; i++) {
calcImpl.increment();
}
}
function classAlgo () {
class Calc {
constructor() {
this.count = 0;
}
increment () {
this.count++;
}
}
var calcImpl = new Calc();
for(i= 0; i < iterations; i++) {
calcImpl.increment();
}
}
perf(closureAlgo);
perf(closureFunctionAlgo);
perf(plainObjectAlgo);
perf(plainObjectCreateAlgo);
perf(objectAlgo);
perf(classAlgo);