const MAX = 10000
const arr = new Array(10000)
const f = () => {}
for (let i = 0; i < MAX;i++) {
arr[i] = true
if (arr[i]) f();
}
const set = new Set()
const MAX = 10000
const f = () => {}
for (let i = 0; i < MAX;i++) {
set.add(i)
if (set.has(i)) f();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array | |
set |
Test name | Executions per second |
---|---|
array | 46686.9 Ops/sec |
set | 2327.6 Ops/sec |
Overview of the Benchmark
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The benchmark in question compares two approaches: creating an array versus creating a set, both for setting 10,000 elements.
Approaches Compared
There are two test cases:
new Array(10000)
constructor. The code then populates the array with values and uses the arr[i]
syntax to access each element.new Set()
constructor. The code then adds 10,000 elements to the set using the set.add(i)
method.Pros and Cons of Each Approach
Pros:
Cons:
arr[i]
.Pros:
set.add(i)
), as it automatically eliminates duplicates.set.has(i)
method.Cons:
Library Used
Neither approach relies on an external library. However, if we consider the inherent properties of JavaScript objects (arrays and sets), we can note that:
new Set()
constructor is only available in ECMAScript 2015+ dialects.Special JS Features/Syntax
There are no specific special features or syntax mentioned in the benchmark. However, it's worth noting that the use of arrow functions (() => {}
) and the for...of
loop (not used explicitly but implied by the context) is a relatively modern JavaScript feature introduced in ECMAScript 2015.
Other Alternatives
For larger-scale benchmarking or more complex scenarios, consider exploring other alternatives:
Keep in mind that each framework or tool has its strengths and weaknesses. MeasureThat.net provides a simple, lightweight way to create and run microbenchmarks, which is particularly suitable for small-scale comparisons like this one.