const a = []
for (let i = 0; i < 30; i++) a.push(i)
const s = new Set()
for (let i = 0; i < 30; i++) s.add(i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.push | |
set.add |
Test name | Executions per second |
---|---|
array.push | 10908222.0 Ops/sec |
set.add | 1910069.6 Ops/sec |
The benchmark provided compares the performance of two different ways to add elements to a collection in JavaScript: using an array's push
method and a Set's add
method. The test specifically uses 30 elements to observe how each approach performs in terms of execution speed.
array.push
:
a
, and then iteratively adds integers from 0 to 29 to it using the push
method.set.add
:
s
, and similarly adds integers from 0 to 29 using the add
method.The results of the latest benchmark indicate that array.push
is significantly faster than set.add
, with execution speeds as follows:
Pros and Cons:
Array with push
:
array.includes()
) can be slower as the size of the array grows, requiring full linear scans.Set with add
:
set.has()
), which operates in constant time on average due to the underlying hash structure.Alternatives:
When you choose between these data structures, consider your specific use cases, including the need for performance versus the requirements for allowing duplicates, accessing elements by index, or managing unique items.
By understanding the differences between using an array versus a Set in JavaScript, software engineers can make informed choices based on performance implications appropriate for their application needs.