v8自定义映射和减少函数的次数比内置函数快

时间:2015-12-27 17:49:43

标签: javascript performance v8

所以这是我的"基准":

function id (el) {return el;}

function fakeMap (arr, fn){
  var ret = new Array(arr.length);
  for (var i = 0; i<arr.length; i++){
    ret[i] = fn(arr[i], i, arr);
  }
  return ret;
}

function arrCopyFor(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < arr.length; i++) {
    ret[i] = arr[i];
  }
  return ret;
}

function arrCopyMap(arr) {
  return arr.map(id);
}

function arrCopyFakeMap (arr) {
  return fakeMap(arr, id);
}

var hugeArray = new Array(20000000);
function buildHugeArray() {
  for (var i = 0; i < hugeArray.length; i++) {
    hugeArray[i] = i;
  }
  print("HugeArr: " + hugeArray.length.toString());
}


function time(fn) {
  var before = Date.now(),
      ret = fn(hugeArray);
  var after = Date.now();
  return (after - before);
}

buildHugeArray();
print("Real map ms:", time(arrCopyMap));
print("Fake map ms:", time(arrCopyFakeMap));
print("For loop ms:", time(arrCopyFor));

我得到的输出:

d8 map.js
HugeArr: 20000000
Real map ms: 1541
Fake map ms: 110
For loop ms: 128

我希望内置更快一点,但事实证明自定义地图的速度提高了10倍以上。我知道这不是一个非常好的基准功能方法,但我不希望这种方法能解释这种巨大的差异。

更具说明性的是相应的减少结果:

function sum (el1, el2) {return el1 + el2;}

function fakeReduce (arr, fn, initial) {
  if (typeof initial === 'undefined') {
    initial = fn[0];
  }
  for (var i = 0; i<arr.length; i++){
    initial = fn(initial, arr[i], i, arr);
  }
  return initial;
}

function arrSumFor(arr) {
  var ret = 0;
  for (var i = 0; i < arr.length; i++) {
    ret += arr[i];
  }
  return ret;
}

function arrSumReduce(arr) {
  return arr.reduce(sum);
}

function arrSumFakeReduce (arr) {
  return fakeReduce(arr, sum);
}

var hugeArray = new Array(20000000);
function buildHugeArray() {
  for (var i = 0; i < hugeArray.length; i++) {
    hugeArray[i] = i;
  }
  print("HugeArr: " + hugeArray.length.toString());
}


function time(fn) {
  var before = Date.now(),
      ret = fn(hugeArray);
  var after = Date.now();
  return (after - before);
}

buildHugeArray();
print("Real reduce ms:", time(arrSumReduce));
print("Fake reduce ms:", time(arrSumFakeReduce));
print("For loop ms:", time(arrSumFor));

输出:

$ d8 reduce.js
HugeArr: 20000000
Real reduce ms: 1339
Fake reduce ms: 84
For loop ms: 43

此外,如果我覆盖数组原型

Array.prototype.reduce = function (fn, initial) {
  return fakeReduce (this, fn, initial);
};

在我得到的文件的顶部:

$ d8 reduce.js
HugeArr: 20000000
Real reduce ms: 109
Fake reduce ms: 84
For loop ms: 39

这是一个v8(或可能是曲轴?)的错误还是我在计算错误?

0 个答案:

没有答案