我有一个简单的代码,创建了一个16*16*256个盒子,其中每个盒子包含10个元素的数组和一个布尔变量。tick方法会增加数组元素,并在一个chunk中的每个盒子中更改布尔值100次。
通过测量时间,我得出以下结果:
Windows x64 node.js 7.4.0:
1 tick: 102.85
Total time(100): 10285
在同一台机器上使用Google Chrome 55:
1 tick: 18.08
Total time(100): 1808
即使底层代码片段比Node快一个数量级,但是Node还是很慢。
代码片段:
1 tick: 22.79
Total time(100): 2279
那么,我该如何让Node工作更快呢?
通过测量时间,我得出以下结果:
Windows x64 node.js 7.4.0:
1 tick: 102.85
Total time(100): 10285
在同一台机器上使用Google Chrome 55:
1 tick: 18.08
Total time(100): 1808
即使底层代码片段比Node快一个数量级,但是Node还是很慢。
代码片段:
1 tick: 22.79
Total time(100): 2279
那么,我该如何让Node工作更快呢?
(function(){
class Box {
constructor() {
this.data = new Array(10);
this.state = false;
}
tick() {
this.state = !this.state;
for(let i = 0; i < this.data.length; i++) {
this.data[i]++;
}
}
}
class Chunk {
constructor() {
this.data = new Array(256);
for(let z = 0; z < this.data.length; z++) {
this.data[z] = new Array(16);
for(let x = 0; x < this.data[z].length; x++) {
this.data[z][x] = new Array(16);
for(let y = 0; y < this.data[z][x].length; y++) {
this.data[z][x][y] = new Box();
}
}
}
}
tick() {
for(let z = 0; z < this.data.length; z++) {
for(let x = 0; x < this.data[z].length; x++) {
for(let y = 0; y < this.data[z][x].length; y++) {
this.data[z][x][y].tick();
}
}
}
}
}
var c = new Chunk();
var count = 100;
var start = new Date().getTime();
for(let i = 0; i < count; i++) {
c.tick();
}
var end = new Date().getTime();
console.log("1 tick: " + (end - start) / count);
console.log("Total time(" + count + "): " + (end - start));
})();