请告诉我,将值推入数组的更快方法是什么?
我写了一个简单的测试来比较push
和a[a.length]=
方法:
推.js:
self.onmessage = function (event) {
var n = Number(event.data),
i,
pushAr = [],
pushStart,
pushDuration,
ar = [],
start,
duration,
message;
// Push
pushStart = new Date();
for (i = 0; i < n; i += 1) {
pushAr.push(i);
}
pushDuration = new Date() - pushStart;
// explicit
start = new Date();
for (i = 0; i < n; i += 1) {
ar[ar.length] = i;
}
duration = new Date() - start;
message = "N = " + n;
message += "\nPush duration: " + pushDuration + "; ";
message += "Length duration: " + duration;
self.postMessage(message);
};
主.js:
var worker = new Worker("push.js"),
i;
worker.onmessage = function (event) {
console.log(event.data);
};
for (i = 4; i < 8; i += 1) {
worker.postMessage(Math.pow(10, i));
}
我得到了以下结果:
铬合金:
N = 10000
Push duration: 0; Length duration: 0
N = 100000
Push duration: 3; Length duration: 5
N = 1000000
Push duration: 56; Length duration: 90
N = 10000000
Push duration: 807; Length duration: 948
苹果浏览器:
N = 10000
Push duration: 1; Length duration: 4
N = 100000
Push duration: 2; Length duration: 2
N = 1000000
Push duration: 27; Length duration: 41
N = 10000000
Push duration: 283; Length duration: 461
火狐:
N = 10000
Push duration: 1; Length duration: 0
N = 100000
Push duration: 2; Length duration: 2
N = 1000000
Push duration: 11; Length duration: 20
N = 10000000
Push duration: 279; Length duration: 412
似乎Array.push
更快,但为什么有些库会使用array length
呢?这种方法有什么好处?为什么 Chrome 这么慢?也许存在一些更快的方法?