var set = new Set();
var obj = new Object();
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
set.add(makeid());
set.has(makeid())
obj[makeid()]="";
if (obj.hasOwnProperty(makeid())) ;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Object |
Test name | Executions per second |
---|---|
Set | 173716.4 Ops/sec |
Object | 156727.2 Ops/sec |
I'd be happy to help you understand what's being tested in this JavaScript microbenchmark.
Overview
The benchmark measures the performance difference between using a Set
data structure and an object (Object
) to store unique identifiers. The test creates 5 random strings (each 5 characters long) and adds them to either a Set
or an object, then checks if each string is present in the collection.
Options Compared
There are two options being compared:
Set
is a built-in JavaScript data structure that stores unique values. It provides fast lookup, insertion, and deletion operations.Pros and Cons of Each Approach
Set
Pros:
Set
uses a hash table to store elements, making lookups constant-time (O(1)).Set
can add or remove elements in O(1) time.Set
ensures that each value is unique.Cons:
Set
only provides basic operations; no methods for adding multiple values at once, etc.Object
Pros:
forEach
, map
, reduce
).Cons:
Set
due to the need to traverse the property chain.Library and Special JS Feature
In this benchmark, there is no explicit library or special JavaScript feature being used. However, it's worth noting that using Set
has become a common pattern in modern web development, especially when dealing with unique identifiers or sets of data.
Benchmark Preparation Code
The script preparation code creates two variables: set
and obj
, both initialized as empty collections (i.e., Set
and Object
). The makeid()
function generates 5 random strings, which are then added to either the set
or obj
.
Individual Test Cases
Each test case consists of a single benchmark definition:
set.add(makeid()); set.has(makeid())
- adds the generated string to the set and checks if it's present.obj[makeid()] = ""; obj.hasOwnProperty(makeid())
- adds the generated string as a property in the object with an empty value, then checks if the property exists.Benchmark Results
The latest benchmark results show the execution time per second for each test case:
These results indicate that the Set
approach is slightly faster than the object approach in this specific benchmark.
Other Alternatives
If you're interested in exploring alternative approaches, some options might include:
Map
(another built-in JavaScript data structure) instead of an object.Keep in mind that these alternatives may not be relevant to the specific requirements of this benchmark, and their results might differ.