push() vs. Fixed Array Experiment
July 21, 2019
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
This was tested with Google Chrome 75. So the V8 engine was used.
Note: These experiments are blocking.
Experiment 1 -
Experiment 2 - Indexing on Fixed Size Array
|Trial||Experiment 1||Experiment 2|
As it turns out, in the average case,
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
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.