var keyCount = 65535
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 = 3000000000000000000+((4000000000000000000*Math.random())|0)
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)
}
for (let i=0; i<keyCount; i++) {
let seed = Math.random()
let key = getConspicuousKey(seed)
a = obj[key]
}
for (let i=0; i<keyCount; i++) {
let seed = Math.random()
let key = getConspicuousKey(seed)
a = map.get(key)
}
for (let i=0; i<keyCount; i++) {
let seed = Math.random()
let key = getConspicuousKey(seed)
a = obj[key]
}
let seed = Math.random()
let key = getConspicuousKey(seed)
a = map.get(key)
let seed = Math.random()
let key = getConspicuousKey(seed)
a = obj[key]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Conspicuous Map lookup | |
Conspicuous Obj lookup | |
Conspicuous Map lookup 2 | |
Conspicuous Obj lookup 2 | |
Single map | |
Single obj |
Test name | Executions per second |
---|---|
Conspicuous Map lookup | 21.4 Ops/sec |
Conspicuous Obj lookup | 13.6 Ops/sec |
Conspicuous Map lookup 2 | 22.6 Ops/sec |
Conspicuous Obj lookup 2 | 13.8 Ops/sec |
Single map | 1377314.5 Ops/sec |
Single obj | 883642.5 Ops/sec |
I'll provide an explanation of the benchmark, its options, pros and cons, and other considerations.
Benchmark Overview
The benchmark measures the performance of two data structures: Maps (JavaScript objects with key-value pairs) and Objects (custom JavaScript objects). The test cases compare the execution time of lookups in both data structures using a similar approach. This allows us to isolate the overhead of using an Object versus a Map for lookups.
Options Compared
The benchmark compares the performance of two approaches:
map.get()
method with a key that is "conspicuous" (i.e., generated by Math.random() * keyCount
and then scaled to fit within an array of 19-digit integers). This approach is used in multiple test cases.map.get()
or obj[key]
method with a simple, fixed key (the first 19 digits of a random integer).Pros and Cons
Considerations
Math.random()
to generate keys introduces variability in the benchmark results, which can make it harder to draw conclusions.Libraries and Special Features
The benchmark uses no external libraries besides the standard JavaScript Map
and Object
constructors. There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
If you want to modify or extend this benchmark, here are some alternative approaches: