var keyCount = 16384
var keys = []
var map = new Map()
var obj = {}
// Hide lookup keys to prevent V8 cheating (AKA Optimizing)
var getConspicuousKey = seed => keys[Math.floor(seed * keyCount)]
// Setup out test objects w/ random values
for (let i=0; i<keyCount; i++) {
let val = Math.random()
let key = Math.random()
keys.push(key)
map.set(key,val)
obj[key] = val
}
for (let i=0; i<keyCount; i++) {
let seed = Math.random()
let key = getConspicuousKey(seed)
a = map.get(key)
if (a) map.delete(key)
}
for (let i=0; i<keyCount; i++) {
let seed = Math.random()
let key = getConspicuousKey(seed)
a = obj[key]
if (a) delete obj[key]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Conspicuous Map lookup & delete | |
Conspicuous Obj lookup & delete |
Test name | Executions per second |
---|---|
Conspicuous Map lookup & delete | 2438.3 Ops/sec |
Conspicuous Obj lookup & delete | 130.9 Ops/sec |
The benchmark you've provided tests the performance of two different data structures in JavaScript for a specific operation: looking up and deleting keys. The two structures being compared are Map and Object.
Map:
Object:
Conspicuous Map lookup & delete:
Math.random()
to select a key helps ensure that the keys are not strictly sequential, preventing the JavaScript engine (V8 in this case) from optimizing the accesses in a way that would skew results.Conspicuous Obj lookup & delete:
Using Arrays: For situations where the order of keys/items matters and the number of entries is small, an array can be used, but lookups will be slower (O(n) complexity).
WeakMap: When dealing with object keys that don’t need to be retained after objects are deleted, WeakMaps offer benefits such as automatic garbage collection for unused keys. However, they do not provide the ability to enumerate their keys.
Set: If the requirement is only to maintain unique values (not key-value pairs), Sets can be an optimal choice. They provide similar performance benefits to Maps for value lookups but do not directly allow for key-value associations.
In summary, when deciding between a Map and an Object, the choice will depend on the requirements around key types, order of elements, and performance considerations. For tasks involving frequent additions, deletions, and lookups, Maps may be the preferable structure based on the results presented in this benchmark.