Why the push method is much slower than entering values ​​through array indices in Javascript

I pretty much don't understand why this test:

http://jsperf.com/push-method-vs-setting-via-key

Shows that

a.push(Math.random()); 

more than ten times slower than

  a[i] = Math.random(); 

Could you explain why this is so? What magical “push” makes it so slow? (or so slowly compared to another valid way of doing this).

EDIT

NOTE. The push test is biased. I increase the size of the array at each iteration! Read the carefully accepted answer!

Benchmark results

+6
source share
3 answers

Could you explain why this is so?

Because your test is ruined. push always adds a to the existing array, making it much larger, and the second test uses only the first 1000 indexes. Using setup is not enough here, you will need to reset the array a before each for loop: http://jsperf.com/push-method-vs-setting-via-key/3 .

In addition, calling the push method can have a small overhead, and it may take extra time to determine the current length of the array compared to using the for-loop index.

Usually there is no reason not to use push - the method exists specifically for this operation and makes it easier to read some code. While several people believe that one version is faster than the other, both are equally optimized in browsers. See Why array.push is sometimes faster than array [n] = value? and Using the push or .length method when adding to an array? - The results change so widely that it does not actually matter. Use what is best understood.

+8
source

This is simply because Google decided to work more on optimizing array indexing than optimizing the push method in Chrome.

If you look at the test results that several more people have tried, you will see that the performance is very different between different browsers and even between different versions of the same browser.

Browsers are currently compiling Javascript code, which means the browser is turning the code into something much faster to run this interpreted Javascript. What the compiler does with the code determines how different ways of doing things work. Different compilers optimize some things better, giving different preliminary results.

+2
source

Because .push () is a function call and the other is a direct assignment. Direct assignment is always faster.

Remember that in javascript, arrays are objects like everyone else. This means that you can assign properties to them.

In the special case of arrays, they have a built-in length property that gets an update behind the scenes (and many other optimizations under the hood, but that doesn't matter right now).

In a normal object, you can do this, but it is not an array:

 var x = { 0: 'a', 1: 'b', 2: 'c' }; 

However, since arrays and hashes are both objects, this is equivalent.

  var x = [ 'a', 'b', 'c' ]; 

Since x is an array in the second case, the length is automatically calculated and available.

0
source

All Articles