I was watching a JS video by Douglas Crockford and he mentioned a way to "push" an item into an array, without using the Array.push
method. It's super simple and something I had never thought of doing, but after doing running a speed test I realize it's slower than Array.push
, which doesn't make much sense to me.
How can something like Array.push
(which does the same thing as array[array.length] = val
, plus other things along with the cost of calling the function itself), be faster than just a plain expression?
Maybe my tests are bad, maybe I have a lack of CS fundamentals here, but if someone can explain the speed differences here I'd really appreciate that. I was simply trying to see if array[array.length] = val
was a faster alternative to Array.push
, but apparently not. g
This is how Array.push
is implemented:
function push(value) {
var len = this.length;
this[len] = value;
len++;
this.length = len;
return len;
}
As you can see, it clearly has much more logic then a simple expression, yet it's faster.
Take a look:
let arr = [],
p1 = performance.now();
for (let i = 1, len = 10; i <= len; i++) {
arr[arr.length] = i;
}
let p2 = performance.now();
console.log(p2 - p1);
Running the example above, I get 0.015000000001236913, or 0.015 for short.
Now let's look at the Array.push
:
let arr = [],
p1 = performance.now();
for (let i = 1, len = 10; i <= len; i++) {
arr.push(i);
}
let p2 = performance.now();
console.log(p2 - p1);
Running the example above, I get 0.010000000002037268, or 0.010 for short.
Array.push
is 0.010, and array[array.length] = val
is 0.015, using the same loop.
How can this be? It makes absolutely no sense to me. What am I missing here?