I was considering ways to create arrays containing a default value using native methods and ended up with
function pushMap(length, fill){
var a = [], b = [];
a.length = length;
b.push.apply(b,a);
return b.map(function(){return fill;});
}
Expecting it to be 2 or 3 times slower than a while loop, as the native methods have to loop twice whereas while loops only once, so I compared it on jsperf against
function whileLengthNew(len, val) {
var rv = new Array(len);
while (--len >= 0) {
rv[len] = val;
}
return rv;
}
and it is actually 18 to 27 times slower (tested with Google Chrome on Ubuntu, browsers/OSs welcome).
What is happening that causes such a big difference?
I would expect that this is due to two major factors:
Memory allocation —
whileLengthNewcreates an array of the correct size first, and then operates on it,pushMapcreates the final array one element at a time withmap. This may cause multiple allocations, especially if the source array is large. (The way that you create the initialaandbarrays is basically irrelevant, sincemapis building up a new array to return anyway — it doesn’t actually change anything inb)Function call overhead — in your call to
map, you are calling a function for every element of the array. This involves quite a lot of overhead; setting up activation records and scope chains, stack manipulation, and passing the return value back. — all of this to access a variable which is constant within the function. On top of that, you have set up a closure, so even accessing thefillvariable is slower than it is in thewhileLengthNewversion.