So here is my "test":
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));
The output I get is:
d8 map.js
HugeArr: 20000000
Real map ms: 1541
Fake map ms: 110
For loop ms: 128
I would expect the built-in to be a little faster, but it turns out that the custom map is more than 10 times faster. I know that this is not a very good way to test functions, but I do not expect the method to take these large differences into account.
Even more significant were the corresponding results to reduce:
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));
Exit:
$ d8 reduce.js
HugeArr: 20000000
Real reduce ms: 1339
Fake reduce ms: 84
For loop ms: 43
Also, if I overwrite the prototype Array, setting
Array.prototype.reduce = function (fn, initial) {
return fakeReduce (this, fn, initial);
};
at the top of the file I get:
$ d8 reduce.js
HugeArr: 20000000
Real reduce ms: 109
Fake reduce ms: 84
For loop ms: 39
Is this a v8 bug (or perhaps cranked?), Or am I finding something wrong?