var to0 = {};
var to1 = {};
var wm = new WeakMap();
var sy = Symbol();
wm.set(to1, 1);
to1[sy] = 1;
wm.set(to0, 1);
to0[sy] = 1;
let r = wm.get(to1);
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 | 59821252.0 Ops/sec |
Symbol Property set | 103560592.0 Ops/sec |
WeakMap get | 57702332.0 Ops/sec |
Symbol Property get | 95234376.0 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark is comparing two approaches: using a WeakMap
data structure and using a symbol property (represented by the Symbol
variable sy
) to store and retrieve values.
Script Preparation Code
The script creates two empty objects, to0
and to1
, and initializes a new WeakMap
instance, wm
. It also declares a symbol variable, sy
.
var to0 = {};
var to1 = {};
var wm = new WeakMap();
var sy = Symbol();
The script then sets up two test cases:
wm.set(to1, 1);
: Sets a value in the WeakMap
.to1[sy] = 1;
: Stores a value using the symbol property.let r = wm.get(to1);
: Retrieves a value from the WeakMap
using the key to1
.let r = to1[sy];
: Retrieves a value using the symbol property.Individual Test Cases
Each test case runs a single benchmark definition, comparing the performance of the two approaches ( WeakMap
and symbol property).
Comparison of Approaches
The pros and cons of these approaches are:
[[Prototype]]
property can be used as keys.Library and Special JS Features
The benchmark uses WeakMap
, which is a built-in JavaScript data structure. No special libraries or modules are required.
No special JS features or syntax are being tested in this benchmark.
Other Alternatives
Alternative approaches to WeakMaps and symbol properties include:
Object
prototype's set
method with a custom object as the key (not recommended due to performance issues).WeakMap
implementation.Keep in mind that WeakMaps are a built-in JavaScript feature and are likely the most efficient and convenient solution for this use case.