let set = new Set();
for (let i = 10000; i < 11000; i++) {
set.add(i);
}
for (let i = 10000; i < 11000; i++) {
set.has(i);
}
let set = {};
for (let i = 10000; i < 11000; i++) {
set[i] = true;
}
for (let i = 10000; i < 11000; i++) {
Object.prototype.hasOwnProperty.call(set, i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Obj |
Test name | Executions per second |
---|---|
Set | 27200.6 Ops/sec |
Obj | 2663.9 Ops/sec |
Overview of the Benchmark
The provided benchmark is designed to compare the performance of two approaches: using a Set
data structure and using an object literal ({}
) with the hasOwnProperty()
method.
Comparison Options
There are two options being compared:
Set
: This approach uses the built-in Set
data structure in JavaScript, which is implemented as a hash table. The add()
method is used to add elements to the set, and the has()
method is used to check if an element is present in the set.hasOwnProperty()
: This approach uses an object literal ({}
) and the hasOwnProperty()
method to store key-value pairs. The for...in
loop is used to iterate over the keys, and the hasOwnProperty()
method is used to check if a key is present in the object.Pros and Cons of Each Approach
Set
:has()
method has an average time complexity of O(1), making it very efficient for large datasets.hasOwnProperty()
:forEach()
, forEachKey()
, etc.).hasOwnProperty()
method has an average time complexity of O(1) in most implementations, but it's not as fast as the has()
method in a Set.Library and Purpose
None of the test cases use a specific library. However, the Set
data structure is a built-in JavaScript feature that can be used without any additional libraries or imports.
Special JS Feature/Syntax
There are no special JS features or syntax mentioned in the benchmark definition. The test cases only use standard JavaScript syntax and built-in methods.
Other Alternatives
If you were to write your own microbenchmark using a similar approach, you might consider adding additional variations, such as:
Array
instead of a SetKeep in mind that the effectiveness of these alternatives would depend on your specific use case and requirements.
Benchmark Preparation Code
The provided Script Preparation Code
is empty, which means that the benchmark is designed to be run directly without any setup. The Html Preparation Code
is also empty, suggesting that no HTML setup or cleanup is required for this benchmark.