在 Chrome 中进行测试时,与 Javascript 中的内置函数相比,反转数组的简单实现速度是其两倍。V8在做什么?这是测试:
var newArr = [];
var newArrDefault = [];
for(var i = 0; i < 10000000; i++){
newArr[i] = i;
newArrDefault[i] = i;
}
var startDefault = new Date();
newArrDefault.reverse();
console.log("Built in method took " + (new Date().getTime() - startDefault.getTime()));
var start = new Date();
for(var i = 0; i < newArr.length / 2; i++){
var tmp = newArr[i];
newArr[i] = newArr[newArr.length-i-1];
newArr[newArr.length-i-1] = tmp;
}
console.log("Custom method took " + (new Date().getTime() - start.getTime()));
版本 20.0.1132.47 Ubuntu 12.04 (144678) 上的结果:
Built in method took 149
Custom method took 71