var keyCount = 16384
var keys = []
var map = new Map()
var weakmap = new WeakMap()
// 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 = {}
keys.push(key)
map.set(key,val)
weakmap.set(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 = weakmap.get(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 = weakmap.get(key)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Conspicuous Map lookup | |
Conspicuous WeakMap lookup | |
Conspicuous Map lookup 2 | |
Conspicuous WeakMap lookup 2 |
Test name | Executions per second |
---|---|
Conspicuous Map lookup | 44.2 Ops/sec |
Conspicuous WeakMap lookup | 46.0 Ops/sec |
Conspicuous Map lookup 2 | 44.6 Ops/sec |
Conspicuous WeakMap lookup 2 | 46.4 Ops/sec |
Measuring the performance of different data structures in JavaScript, such as Map
and WeakMap
, is crucial for optimizing applications.
Benchmark Definition
The benchmark tests the performance of looking up values in a Map
versus a WeakMap
. A Map
is an object that stores key-value pairs, while a WeakMap
is similar but allows keys to be garbage collected when they are no longer referenced.
Options Compared
Two options are compared:
Map
lookup: This option uses the get()
method of the Map
interface to retrieve values based on their keys.WeakMap
lookup: This option uses the get()
method of the WeakMap
interface to retrieve values based on their keys.Pros and Cons
Map
:WeakMap
:Library
In this benchmark, neither Map
nor WeakMap
use any external libraries. They are built-in JavaScript data structures.
Special JS Feature/Syntax
This benchmark uses some advanced JavaScript features:
getConspicuousKey()
function to generate a random key.for...of
loops to define small anonymous functions.map
and weakmap
objects to create computed properties.However, these features are not specific to JavaScript and are widely used in many programming languages.
Other Alternatives
If you're interested in comparing performance between different data structures in JavaScript, here are some alternatives:
Set
vs WeakSet
: Compare the performance of looking up values in a Set
versus a WeakSet
.Array
vs Int8Array
: Compare the performance of accessing elements in an Array
versus an Int8Array
.JSON.parse()
vs `JSON.stringify()```: Compare the performance of parsing JSON strings using JSON.parse()
versus stringifying JSON objects using JSON.stringify()
.