var to0 = {};
var to1 = {};
var wm = new WeakMap();
var sy = Symbol();
wm.set(to1, 1);
to1[sy] = 1;
window.r = 0
wm.set(to0, 1);
to0[sy] = 1;
r = wm.get(to1);
r = to1[sy];
r = Object.getOwnPropertyDescriptor(to1, sy).value;
r = Object.hasOwn(to1, sy) ? to1[sy] : undefined;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
WeakMap set | |
Symbol Property set | |
WeakMap get | |
Symbol Property get | |
Symbol Property get (from own descriptor) | |
Symbol Property get (if hasOwn) |
Test name | Executions per second |
---|---|
WeakMap set | 14126756.0 Ops/sec |
Symbol Property set | 14978403.0 Ops/sec |
WeakMap get | 7216884.5 Ops/sec |
Symbol Property get | 7425304.5 Ops/sec |
Symbol Property get (from own descriptor) | 4879848.0 Ops/sec |
Symbol Property get (if hasOwn) | 3861038.2 Ops/sec |
Measuring performance differences between various JavaScript approaches can be complex, but I'll break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of three approaches for accessing Symbol properties:
[]
syntax to access a symbol property on an object.get()
method.Object.getOwnPropertyDescriptor()
function to retrieve the value of a symbol property from its owning object's descriptor.Object.hasOwn()
function to check if an object has a symbol property, and then retrieving it using the []
syntax.Benchmark Script
The script preparation code sets up two objects (to0
and to1
) and creates a WeakMap (wm
) with a symbol key (sy
). The script also defines some test functions that will be used to benchmark each approach.
Benchmark Test Cases
The test cases are designed to execute the following scenarios:
wm.set(to0, 1)
.to1[sy] = 1
).r = wm.get(to1)
.to1[sy]
) directly.Object.getOwnPropertyDescriptor()
to retrieve the value of the symbol property from its owning object's descriptor.Object.hasOwn()
, and then retrieve it using the []
syntax.Performance Comparison
The benchmark measures the performance of each approach by executing each test case repeatedly, and reports the average number of executions per second for each browser version.
Pros and Cons of Each Approach
Symbol()
with a string value).Object.hasOwn()
.Other Considerations
Alternatives
Other alternatives for accessing symbol properties or caching/retrieving data include:
Object.keys()
or Object.getOwnPropertyNames()
to iterate over own property names.