var
map = new Map(),
set = new Set(),
arr = [],
sym = Symbol(),
uid = "some-uid",
item = {}; // not in any
// Create
for (var i = 0; i < 5000; ++i)
{
var obj = {};
map.set(obj, true);
set.add(obj);
arr.push(obj);
obj[sym] = true;
obj[uid] = true;
}
function mapHas(thing)
{
return map.has(thing);
}
function setHas(thing)
{
return set.has(thing);
}
function arrHas(thing)
{
return arr.indexOf(thing) >= 0;
}
function symHas(thing)
{
return thing[sym];
}
function uidHas(thing)
{
return thing[uid];
}
function conHas(thing)
{
return false;
}
mapHas(item);
setHas(item);
arrHas(item);
symHas(item);
uidHas(item);
conHas(item);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
set | |
arr | |
symbol | |
uid | |
control |
Test name | Executions per second |
---|---|
map | 3519979.5 Ops/sec |
set | 3270291.5 Ops/sec |
arr | 333034.3 Ops/sec |
symbol | 3358327.0 Ops/sec |
uid | 3221204.5 Ops/sec |
control | 4663772.0 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of various data structures in JavaScript: Map
, Set
, Array
, and Symbol
. The test creates an object with unique identifiers (UID
) and iterates over 5,000 objects to populate each data structure. The benchmark then runs a series of functions that check if a specific object exists within each data structure.
Data Structures Compared
Options Compared
Set
only stores unique values, while Map
allows key-value pairs.Map
: Can store additional information with each key-value pair, which might be useful in certain scenarios.Map
: More memory-intensive due to the storage of keys and values.Array
is fixed-size, while Map
can grow dynamically.Array
: Fixed-size, which might be beneficial in terms of memory usage and performance for certain use cases.Array
: Does not support key-value pairs or fast lookups by value.Set
is designed for fast membership testing, while Array
requires explicit checks.Set
: Fast membership testing and automatic removal of duplicates.Set
: Does not support indexing or random access.Library Used
The benchmark uses the built-in Map
, Set
, Array
, and Symbol
data structures in JavaScript. These are implemented in V8, the JavaScript engine used by Google Chrome.
Special JS Feature/Syntax
This benchmark does not use any special JavaScript features or syntax beyond what is necessary for the test case.
Other Alternatives
For those who may be interested in exploring alternative data structures:
Map
that only stores weak references to keys, which can help prevent memory leaks.Set
that only stores weak references to values, which can help prevent memory leaks.Keep in mind that the choice of data structure ultimately depends on the specific requirements and constraints of your use case.