const set = new Set()
for (let i = 0; i < 1000; i++) {
set.add(i)
}
const set = {}
for (let i = 0; i < 1000; i++) {
set[i] = 1
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set.add | |
object add |
Test name | Executions per second |
---|---|
set.add | 61939.2 Ops/sec |
object add | 376499.8 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark definition is represented by two JSON objects, which describe the individual test cases. In this case, we have only two test cases:
set.add
: This test case creates a new Set object and adds 1000 elements to it using the add()
method.object add
: This test case creates an empty object and assigns 1000 values to its keys using bracket notation ([i] = 1
).Options Compared
The benchmark compares two approaches:
set.add
)object add
)Pros and Cons of Each Approach
set.add
)object add
)Library Usage
There is no explicit library usage mentioned in the benchmark definition. However, note that some older browsers may have issues with Sets natively.
Special JS Features or Syntax
The benchmark uses JavaScript's array-like syntax ([i] = 1
) to simulate an object with array-like behavior. This syntax is not exclusive to modern JavaScript and has been supported for a long time, but it's worth noting that more concise alternatives like set[i] = 1
could also be used.
Other Alternatives
If you're looking for alternative approaches, consider the following:
Keep in mind that these alternatives may not be as widely supported or well-suited to your specific use case.