class Obj {
constructor() {
this.propA = ~~(Math.random() * 255 + 0.5);
this.propB = ~~(Math.random() * 300 + 0.5);
}
}
const arr1 = new Array(100000);
for (var i = 0; i < 100000; i ++) {
arr1[i] = new Obj();
}
function test1() {
let start = new Date();
for (var times = 0; times < 1000; times ++) {
let n = 0;
for (var i = 0; i < 100000; i++) {
if (arr1[i].propA > arr1[i].propB) {
n += 1;
//arr1[i].propB = arr1[i].propA; //<-- try uncomment it
}
}
}
console.log(new Date() - start + 'ms');
}
test1();Run Code Online (Sandbox Code Playgroud)
将此代码粘贴到开发人员工具(或新的.html文件).
在我的电脑上(win7 x64,chrome 63)它打印1200-1600ms.
但是,当我取消注释代码时,它只打印500-700毫秒.
我不知道为什么会发生......
我不知道为什么会发生......
因为在第一次之后的时候
arr1[i].propB = arr1[i].propA;
Run Code Online (Sandbox Code Playgroud)
从下一次迭代开始执行
if (arr1[i].propA > arr1[i].propB)
Run Code Online (Sandbox Code Playgroud)
将是false,因此该行n += 1;不会被执行.
既然你是通过更换一个节能操作增量,分配与唯一的任务,你会看到在速度上的提高.
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |