var arr = [];
new Array(1000).fill(1).forEach((item) => { arr = [arr, item] })
var arr = [];
new Array(1000).fill(1).forEach((item) => { arr.push(item) })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
push |
Test name | Executions per second |
---|---|
spread | 1192.3 Ops/sec |
push | 142978.6 Ops/sec |
I'd be happy to explain what's being tested in the provided benchmark.
Benchmark Overview
The benchmark compares two approaches for adding elements to an array: using the spread operator (...
) and using the push
method. The benchmark is designed to test which approach is faster on a large array of 1000 elements.
Options Compared
Two options are being compared:
...
) to add elements to an array. This operator creates a new array by copying elements from an existing array and spreading them out.push
method to add elements to an array. This method adds one or more elements to the end of an array.Pros and Cons
Here are some pros and cons of each approach:
Spread Operator:
Pros:
Cons:
Array.prototype.concat
)Push Method:
Pros:
Cons:
Library Usage
There is no library used in this benchmark.
Special JS Feature/Syntax
The benchmark uses a JavaScript feature that is widely supported: the spread operator (...
).
Other Considerations
When choosing between these two approaches, consider the following:
push
method might be more efficient due to cache optimization.Alternatives
If you're interested in exploring other alternatives for adding elements to an array, here are some options:
Set
data structure to add elements efficiently.These alternatives might be useful in specific situations, but they often come with their own trade-offs and considerations.