var to0 = {};
var to1 = {};
var wm = new Map();
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 | 6627580.0 Ops/sec |
Symbol Property set | 6686966.5 Ops/sec |
WeakMap get | 6554743.0 Ops/sec |
Symbol Property get | 7040482.5 Ops/sec |
Let's break down the provided JSON data and explain what's being tested, compared, and considered in this JavaScript microbenchmark.
Benchmark Definition
The benchmark measures the performance difference between using Symbol
properties versus regular property names when accessing or setting values on an object. The benchmark uses a WeakMap (wm
) and a plain object (to0
and to1
) to store key-value pairs.
Script Preparation Code
The script prepares two objects: to0
and to1
, which are assigned to the variables var to0 = {};
and var to1 = {};
. Additionally, it creates a WeakMap (wm
) and a Symbol (sy
) using var wm = new Map();
and var sy = Symbol();;
.
The script then sets a key-value pair on the WeakMap using wm.set(to1, 1);
, which is equivalent to setting a property on to0
or to1
with the symbol as its name.
Html Preparation Code
There is no HTML preparation code provided in this benchmark.
Individual Test Cases
The benchmark consists of four test cases:
wm.set(to0, 1);
, which sets a key-value pair on the WeakMap.to0[sy] = 1;
, which sets a property on to0
with the symbol as its name.let r = wm.get(to1);
, which retrieves a value from the WeakMap using its key (to1
).let r = to1[sy];
, which retrieves a value from an object (to1
) using its property with the symbol as its name.Comparison
The benchmark compares the performance of accessing or setting values on objects using either regular property names or Symbol properties. The test cases measure the time taken for each operation (set and get).
Pros and Cons
Using Symbol
properties has several advantages:
However, there are also some potential drawbacks:
On the other hand, using regular property names has its own advantages and disadvantages:
Libraries Used
The benchmark uses the Map
class from JavaScript's built-in object model (var wm = new Map();
) to create the WeakMap. It does not use any external libraries for this purpose.
Special JS Feature or Syntax
The benchmark utilizes the Symbol feature in JavaScript, which is a relatively modern addition to the language (introduced in ECMAScript 2015). Symbols are unique, immutable objects that can be used as property names or values in objects. The benchmark tests the performance of using symbols versus regular property names.
Alternatives
If you're looking for alternatives to this benchmark or want to explore other approaches to measuring JavaScript performance, consider the following: