<!--your preparation HTML code goes here-->
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
const arr = new Array(4000).fill(0,1,4000)
const arr1 = []
arr1.push(arr)
const arr1 = []
for (const element of arr){
arr1.push(element)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Push | |
Spread |
Test name | Executions per second |
---|---|
Push | 118939.9 Ops/sec |
Spread | 64547.9 Ops/sec |
The benchmark compares two different methods of adding elements to an array in JavaScript: using the push()
method with the spread operator (...
) and using a for-of loop with push()
. The benchmark aims to measure which of these two approaches performs better in terms of execution speed.
Push:
const arr1 = []\r\narr1.push(...arr)
arr
when adding them to arr1
. The spread operator allows the elements of arr
to be 'spread' into push()
, enabling all elements to be pushed at once.Spread:
const arr1 = []\r\nfor (const element of arr){\r\n arr1.push(element)\r\n}\r\n
arr
and individually pushes each element to arr1
. It uses a standard for-of
loop to traverse the array and applies the push()
method sequentially for each item.push(...arr)
):Pros:
Cons:
Pros:
Cons:
push()
for each element in the array.From the results, it is evident that the use of the spread operator (push(...arr)
) significantly outperforms the for-of
loop method in this specific case, with nearly double the executions per second.
Other than the methods tested, array concatenation can be performed using Array.prototype.concat()
or leveraging functional approaches such as map()
or reduce()
, though they are generally less performant for this use case. Each alternative comes with its own trade-offs in terms of readability, performance, and memory utilization, which should be carefully weighed against the specific requirements of the project at hand.