var array = [].fill(0, 10, 100)
var array2 = [].fill(0, 20, 100)
array.push(array2)
array = [array, array2]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
push | |
spread |
Test name | Executions per second |
---|---|
push | 4872102.0 Ops/sec |
spread | 2852153.8 Ops/sec |
Let's break down the benchmark definition and test cases.
What is being tested?
MeasureThat.net is testing two approaches for updating an array: using array.push(...array2)
and using the spread operator (array = [...array, ...array2]
). The goal of this benchmark is to compare the performance of these two methods in updating an array with a large number of elements.
Options being compared
There are only two options being compared:
array.push(...array2)
: This method uses the spread operator (...
) to add all elements from array2
to the end of array
. The push()
method is called on the resulting array.array = [...array, ...array2]
: This method uses the spread operator (...
) to create a new array that combines array
and array2
, and then assigns it back to array
.Pros and Cons of each approach
array.push(...array2)
:array = [...array, ...array2]
:push()
mode, and is generally faster.Library usage
There is no library being used in this benchmark. The test cases only involve JavaScript core functionality.
Special JS feature or syntax
The use of the spread operator (...
) is a special JavaScript feature introduced in ECMAScript 2015 (ES6). It allows for creating new arrays by spreading elements from existing arrays.
Other alternatives
Before adopting either approach, it's worth noting that other methods could be used to update an array:
array.concat(array2)
: This method creates a new array and concatenates array
and array2
. While not as efficient as the spread operator or push mode, it is still widely supported.Array.prototype.splice()
: This method updates array
in place by replacing a portion of its elements with elements from array2
.The choice of approach ultimately depends on the specific use case and personal preference.
Keep in mind that this benchmark only tests performance, not code readability or maintainability. Depending on the context, other factors might be more important when choosing an array update method.