var keys = [];
var prefix = 'someKeyPrefix';
var obj = {};
var map = new Map();
var set = new Set();
for (var i = 0; i < 300; i++) {
var key = prefix + i;
keys.push(key);
if (i % 3) {
obj[key] = true;
map.set(key, true);
set.add(key);
}
}
for (const key of keys) {
var val = obj[key]
}
for (const key of keys) {
var has = key in obj
}
for (const key of keys) {
var val = map.get(key)
}
for (const key of keys) {
var has = map.has(key);
}
for (const key of keys) {
var has = set.has(key);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Get from Object | |
Has key in Object | |
Get from Map | |
Has key in Map | |
Has key in Set |
Test name | Executions per second |
---|---|
Get from Object | 29193.1 Ops/sec |
Has key in Object | 28236.9 Ops/sec |
Get from Map | 36934.6 Ops/sec |
Has key in Map | 37241.9 Ops/sec |
Has key in Set | 36461.9 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark that tests access patterns for different data structures: objects, maps, and sets. The benchmark is designed to measure the performance of iterating over these data structures and checking if a key exists.
Script Preparation Code
The script preparation code creates:
obj
) and an array of keys (keys
).map
) and a set (set
) with no initial values.keys
array.Benchmark Definition
The benchmark definition consists of six test cases:
keys
and access the value associated with each key in obj
.keys
and check if each key exists in obj
using the in
operator.keys
and retrieve the value associated with each key in map
.keys
and check if each key exists in map
using the has
method.keys
and check if each key exists in set
using the has
method.Comparing Options
The benchmark compares the performance of accessing keys in objects, maps, and sets using different methods:
in
.get
method.has
method.Pros and Cons
Other Considerations
Alternatives
If you want to explore alternative approaches or data structures, consider:
WeakMap
instead of Map
for faster lookups in JavaScript engines that support them.Keep in mind that the best approach depends on your specific use case and requirements. Experimenting with different data structures and access patterns can help you find the most efficient solution.