var to0 = {};
var to1 = {};
var wm = new WeakMap();
var sy = Symbol();
wm.set(to1, 1);
to1[sy] = 1;
for(let i=900;--i;) wm.set(to0, 1);
for(let i=900;--i;) to0[sy] = 1;
for(let i=900;--i;) {let r = wm.get(to1);}
for(let i=900;--i;) {let r = to1[sy];}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
WeakMap set | |
Symbol Property set | |
WeakMap get | |
Symbol Property get |
Test name | Executions per second |
---|---|
WeakMap set | 16791.4 Ops/sec |
Symbol Property set | 18412.7 Ops/sec |
WeakMap get | 16242.6 Ops/sec |
Symbol Property get | 18481.1 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Context
The benchmark measures the performance of two different approaches: using WeakMap
(a built-in JavaScript object that stores mappings of keys to values, with the key being an object that can be garbage collected) and using a symbol property (a unique identifier for an object's property).
Options Compared
In this benchmark, we have four test cases:
WeakMap
.WeakMap
.Pros and Cons
Library and Purpose
In this benchmark, we don't have a specific library being used. However, WeakMap
is a built-in JavaScript object that provides an efficient way to store mappings of keys to values.
Special JS Feature or Syntax
The use of symbols (sy
) in the benchmark introduces a special feature in JavaScript: symbol properties. Symbols are unique identifiers for objects' properties and provide an alternative to string-based property names.
In this benchmark, symbols are used as property names to measure their performance compared to WeakMap
.
Other Considerations
WeakMap
relies on garbage collection to manage the keys and values. This can lead to unpredictable behavior if the system is under memory pressure.WeakMap
and symbol properties introduce some overhead due to their creation and resolution.Alternatives
If you need to measure performance for other use cases, consider alternatives like: