2

在 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
4

1 回答 1

2

为了好玩,我像这样实现了规范:

var upper, upperExists, lowerExists, lowerValue, upperValue;

for(var lower = 0, len = newArr.length >>> 0, middle = Math.floor(len / 2); lower != middle; ++lower) {
    upper = len - lower - 1;
    lowerValue = newArr[lower];
    upperValue = newArr[upper];
    lowerExists = newArr.hasOwnProperty(lower);
    upperExists = newArr.hasOwnProperty(upper);

    if (lowerExists && upperExists) {
        newArr[lower] = upperValue;
        newArr[upper] = lowerValue;
    } else if (upperExists) {
        newArr[lower] = upperValue;
        delete newArr[upper];
    } else if (lowerExists) {
        newArr[upper] = lowerValue;
        delete newArr[lower];
    }
}

jsperf 可以在这里找到。

它包含一大堆代码来处理丢失的条目,这就是为什么它比本机代码和您的代码都慢得多的原因(一些优化可能是可能的,但它不会对性能产生足够的影响)。不过,您的代码和本机实现之间的性能差异并不是很确定。

在大多数情况下,数组是一个连续的值块,它们之间没有间隙,所以你应该对这种代码安全;只要你知道区别:)

于 2012-11-19T03:11:00.490 回答