19

I don't understand why this test :

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

Shows that

 a.push(Math.random());

is over ten times slower than

 a[i] = Math.random();

Could you explain why this is the case ? What magic "push" do that make it so slow ? (or so slow compared to other valid method of doing that).

EDIT

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

Benchmark results

codemonkey
  • 7,325
  • 5
  • 22
  • 36
Paweł Brewczynski
  • 2,665
  • 3
  • 30
  • 43
  • 1
    What is faster: an assignment or a function call which looks up the length of an array and performs an assignment? – Fabrício Matté Jan 10 '14 at 01:35
  • There is a much smaller difference between the two on Firefox. – Ken Herbert Jan 10 '14 at 01:37
  • @FabrícioMatté Do you suggest that "looking up the length" is so tremendously expensive !? – Paweł Brewczynski Jan 10 '14 at 01:38
  • 1
    @bluesm no, but it is an overhead which a regular assignment doesn't have. Also, `.push()` accepts N arguments to push to the end of the array. Try to code a polyfill for `Array.prototype.push` as if it didn't exist and you will see that it is relatively more complicated than a simple assignment. `=]` – Fabrício Matté Jan 10 '14 at 01:39
  • Please refer http://stackoverflow.com/questions/16952605/array-pushelement-vs-arrayarray-length-element – Shabeer Mothi Jan 10 '14 at 01:41
  • 1
    See also http://stackoverflow.com/questions/614126/why-is-array-push-sometimes-faster-than-arrayn-value which asks the exact opposite question – Barmar Jan 10 '14 at 01:46
  • It's 2017 and a.push() is the fastest on Chrome 59 on macOS: https://jsperf.com/array-push-vs-unshift-vs-direct-assignment/2 – Jonathan Lin Jul 22 '17 at 06:47
  • Setting the length of the array and using direct assignment is faster than using push (Safari and Chrome): https://jsperf.com/push-method-vs-setting-via-key/10 It may be because the javascript runtime is typically implemented in C, and does pre-allocation based on some heuristics. See points 1 and 2 here: https://www.quora.com/How-are-javascript-arrays-implemented-internally/answer/Kiran-651 – Magne Apr 24 '20 at 15:15

3 Answers3

24

Could you explain why this is the case?

Because your test is flawed. The push does always append to the existing a array making it much larger, while the second test does only use the first 1000 indices. Using the setup is not enough here, you would have to reset the a array before every for-loop: http://jsperf.com/push-method-vs-setting-via-key/3.

Apart from that, the method call to push might have a little overhead, and determining the current array length might need additional time compared to using the index of the for-loop.

Usually there is no reason not to use push - the method is there for exactly that operation and makes some code easier to read. While a few people think one version is faster than the other, both are equally optimized in browsers. See Why is array.push sometimes faster than array[n] = value? and Using the push method or .length when adding to array? - results vary so wide that it's actually irrelevant. Use what is better to understand.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Making it much bigger, and then allocating memory which is incredibly expensive? – Paweł Brewczynski Jan 10 '14 at 01:40
  • @Bergi Not sure but I'm not seeing any flaw there. `var a = [];` runs before each clocked test loop. – Fabrício Matté Jan 10 '14 at 01:43
  • 2
    @bluesm: yes, the memory allocation is what kills the `push` version. – James Porter Jan 10 '14 at 01:44
  • 1
    @FabrícioMatté: Yes, each *test loop*. It's run once, then the test (the 1000-times-loop) is run multiple times and execution time of that is measured. This process is reapeated to get an average runtime. – Bergi Jan 10 '14 at 01:46
  • Oh my interpretation was each test loop iteration but I guess you're right. – Fabrício Matté Jan 10 '14 at 01:46
  • 1
    @FabrícioMatté: Look at http://jsperf.com/push-method-vs-setting-via-key/5. You see what I mean? Setup is done once before lots of single tests. – Bergi Jan 10 '14 at 01:52
  • 1
    @Bergi yes I see what you mean. But wh------ ow shit I'm retarded. I added the console.log to the wrong test alright deleting some comments to reduce clutter. Here's the proper test which proves your point: http://jsperf.com/push-method-vs-setting-via-key/4 – Fabrício Matté Jan 10 '14 at 01:55
  • @Bergi I wonder why jsPerf doesn't have part that would be used to clean after EACH test. – Paweł Brewczynski Jan 11 '14 at 22:48
  • Setting the length of the array `var array = new Array(n)` and using direct assignment `array[i] = value` _is_ actually faster than using `array.push(value)` (Safari and Chrome): https://jsperf.com/push-method-vs-setting-via-key/10 It may be because the javascript runtime is typically implemented in C, and does pre-allocation based on some heuristics. See points 1 and 2 here: https://www.quora.com/How-are-javascript-arrays-implemented-internally/answer/Kiran-651 – Magne Apr 24 '20 at 15:11
  • @Magne Yes, in some engines and for some heuristics. I just ran the benchmark you linked on a Chromium-like and `push` was faster (though not a lot). Preallocation might sometimes be beneficial, other times the creation of empty slots degrades usage performance afterwards. In any case, this question was about a scenario where `push` and index assignment are equivalent, and I think my answer still holds. – Bergi Apr 24 '20 at 15:23
4

That's simply because Google decided to put more work into optimising array indexing than optimising the push method in Chrome.

If you look at the test results now that a few more people have tried it, you see that the performance differes quite a lot between different browsers, and even between different versions of the same browser.

Nowadays browsers compile the Javascript code, which means that the browser turns the code into something that is much faster to run that interpreted Javascript. What the compiler does with the code determines how different ways of doing things performs. Different compilers optimise certain things better, which gives the different preformances.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • It seams that it has been fixed in chrome 72. http://jsperf.com/push-method-vs-setting-via-key/3 source: Bergi – EPurpl3 Nov 05 '19 at 12:37
1

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

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

In the special case of arrays, they have a built-in length property that gets update behind the scenes (and lots of other optimizations under the hood, but that's not important right now).

In a regular object, you can do this but its 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, length is automatically calculated and available.

Geuis
  • 41,122
  • 56
  • 157
  • 219