我想查看在javascript中向数组添加元素的速度更快:
我在我的Linux Mint 16,Firefox 37.0.2
上运行它1和2比3好多了。
当我跑100,000次时1明显好于2.
然而,当我运行10,000,000时,结果却被逆转了。 对此有何解释?
var amount = 1000000;
var iter = 11;
var a = new Array(amount);
var b = new Array(amount);
var results = [];
for (j=1; j<iter; j++) {
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = [2,2,2,2,2];
}
results.push("quintuple primitive insert attempt " + j + " took " +
eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = 2;
a[i+1] = 2;
a[i+2] = 2;
a[i+3] = 2;
a[i+4] = 2;
}
results.push("single primitive insert with inline inc attempt " + j +
" took " + eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i++) {
a[i] = 2;
}
results.push("single primitive insert with single iterator attempt " +
j + " took " + eval(new Date().getTime() - clock) + "ms");
}
此处演示了代码:
http://jsfiddle.net/lash/cL3wewj4/
(我也尝试使用同源和异构数组来插入内容,其中2总是最好的。尝试在同一个jsfiddle源中,注释掉)
答案 0 :(得分:0)
你需要花时间去做不同的事情:
首先,您需要创建一个矩阵,其位置i%5 = 0的元素包含五个元素的数组。其余元素(i%5!= 0)未定义。此数组的长度取决于数量,因为您在每次迭代中添加到变量i
五并且数组末尾的某些元素可能未初始化(直接或间接)
for (i = 0; i < amount; i += 5) {
a[i] = [2, 2, 2, 2, 2];
}
其次,你要创建一个元素都等于2的数组。
for (i = 0; i < amount; i += 5) {
a[i] = 2;
a[i + 1] = 2;
a[i + 2] = 2;
a[i + 3] = 2;
a[i + 4] = 2;
}
第三,你和两个人一样。
for (i=0; i< amount; i++) {
a[i] = 2;
}
由于一个不同于2和3,因此结果没有意义。