<!--your preparation HTML code goes here-->
let o, m, w, owm;
const map = new Map();
const obj = Object.create(null);
const wm = new WeakMap();
const wm2 = new WeakMap();
const objSet = (ob, k, v)=>{
ob[k] = v;
return ob;
};
let data = Object.create(null);
wm.set(data, new Map());
wm2.set(data, Object.create(null));
for (let i = 65; i < 90; i++) {
let t = String.fromCharCode(i);
obj[t] = i;
map.set(t, i);
wm.set(data, (wm.get(data)).set(t, i));
wm2.set(data, objSet(wm2.get(data), t, i));
}
o = obj['M'];
m = map.get('M');
w = wm.get(data).get('M');
owm = wm2.get(data)['M'];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object | |
Map | |
Map in WeakMap | |
Object in WeakMap |
Test name | Executions per second |
---|---|
Object | 8553419.0 Ops/sec |
Map | 8156600.0 Ops/sec |
Map in WeakMap | 7180517.0 Ops/sec |
Object in WeakMap | 7575181.0 Ops/sec |
The benchmark defined in the provided JSON tests the performance of four different data access methods within JavaScript: accessing properties from an object, retrieving values from a JavaScript Map
, and fetching values from two types of WeakMap
, one containing a Map
and another containing a plain object. Each method is executed multiple times, and the results are measured in terms of executions per second.
Object Access (o = obj['M'];
)
Map Access (m = map.get('M');
)
Map
. Maps are a more flexible key-value store and can handle various data types as keys.Map
.Map in WeakMap (w = wm.get(data).get('M');
)
Map
that is stored within a WeakMap
. A WeakMap
introduces memory safety since the keys are weakly held, allowing for garbage collection.WeakMap
prevents memory leaks in long-lived applications where the existence of keys should not prevent garbage collection (i.e., when the key object is no longer reachable).Map
increases complexity and can affect performance due to multiple lookups (first in WeakMap
, then in the nested Map
).Object in WeakMap (owm = wm2.get(data)['M'];
)
WeakMap
.WeakMap
. The direct object property access is quick once you retrieve the object.WeakMap
, making it more complex to access the property compared to a straightforward object access.The results show the following executions per second for each test:
Observations:
Map
.WeakMap
structures, whether they contain an object or a Map
, results in decreased performance due to the additional layer of indirection required to reach the desired value.Map
for dynamic key scenarios and maintain order.Proxy
may be viable, impacting performance differently based on implementation.Set
can be paired appropriately with WeakMap
.Overall, while different approaches have their own pros and cons, the choice depends on the specific use case requirements around memory management, key types, property access patterns, and performance metrics.