3

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?

13
  • 1
    Here is the comprehensive test and results for your reference - blog.scottlogic.com/2010/10/15/… Commented Aug 24, 2016 at 18:05
  • What does performance.now() do? Commented Aug 24, 2016 at 18:08
  • Awesome, thanks for the reference. It's funny that the only browser Array.push is slower than array[array.length] = val is Chrome, which is the one I tested on :P. Commented Aug 24, 2016 at 18:09
  • 1
    @Ibu performance.now(): developer.mozilla.org/en-US/docs/Web/API/Performance/now Commented Aug 24, 2016 at 18:13
  • 1
    How often did you run these tests? Did you try them in different orders? Did you do warmups? And clearly a loop with 10 iterations, measuring about 10µs, is hardly significant. Commented Aug 24, 2016 at 18:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.