Array push() vs. Fixed Array Experiment

What is the performance between the two? Let's answer that question.


For this experiment, we want to find out whether, or not there is a significant performance difference between appending an element to an array using Array.prototype.push, or using a array indexing to assign the element to a fixed-sized array.

For both experiments, MAX_SIZE = 100000 array elements will be appended to the array. A total of TOTAL_RUNS = 1000 will be performed to append MAX_SIZE elements to the array.

In order to keep the memory footprint low, and only interest is to measure the time it takes to add elements, the push experiment will reassign an empty array after every run. For the fixed-array experiment, the currIndex will be reassigned to 0.

This was tested with Google Chrome 75. So the V8 engine was used.

Note: These experiments are blocking.

Experiment 1 - Array.prototype.push

Experiment 2 - Indexing on Fixed Size Array


In my case, here are some of the results I had over 10 trials:
Trial Experiment 1 Experiment 2
1 2520.2850 746.2550
2 2522.1900 785.1450
3 2546.1150 804.0600
4 2581.1350 786.3850
5 2559.6750 785.3050
6 2541.3200 752.4950
7 2574.9300 782.2100
8 2558.7050 791.5350
9 2549.8200 768.5550
10 2570.2650 787.7500

As it turns out, in the average case, Array.prototype.push is almost 3.2x slower than using a fixed-sized array with indexing. Why is that?

What seems to be the case is that if an arrays are treated more like lists, such as the Java ArrayList, for example. This means that an array without a fixed known size that is initially allocated like the following:

var arr = [];

Has a fixed-block of memory allocated for it to some size. When push is called, the array will be resized if there is not enough space within this block of memory to store the new element. Therefore a resizing routine is executed to create a bigger array, and then copy the existing elements to this new array before finally appending the new element to the new array. Of course, the existing array reference is then updated to reference this new array.

Now for arrays in which we already know the number of elements we need to add to, it is best to just have a setup routine that can allocate the total number of elements first, and keeping track of the current index when appending to the array. This way, we can avoid the resizing routine performed, and will save a lot of execution time.

Fixed arrays won't work if your arrays become too large though, so it really depends on your use-case here on which method to actually use.

Source Code



  • V8 - source code
  • How do JavaScript arrays work under the hood?
  • ECMA-262 Spec - Array.prototype.push(... items)