class CustomWeakMap {
constructor(relationKey = '__relation') {
this.relationKey = relationKey;
}
// 设置键值对 - 使用直接属性赋值以提高性能
set(key, value) {
key[this.relationKey] = value;
return this;
}
// 获取键对应的值
get(key) {
return key[this.relationKey];
}
// 检查键是否存在
has(key) {
return this.relationKey in key;
}
// 删除键值对
delete(key) {
return delete key[this.relationKey];
}
}
var to0 = {};
var to1 = {};
var to2 = {}
var wm = new WeakMap();
var sy = Symbol();
var cy = new CustomWeakMap();
wm.set(to1, 1);
to1[sy] = 1;
cy.set(to2,1)
wm.set(to0, 1);
to0[sy] = 1;
let r = wm.get(to1);
let r = to1[sy];
cy.set(to2, 1);
let r = cy.get(to2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
WeakMap set | |
Symbol Property set | |
WeakMap get | |
Symbol Property get | |
CustomWeakMap set | |
CustomWeakMap get |
Test name | Executions per second |
---|---|
WeakMap set | 102614104.0 Ops/sec |
Symbol Property set | 173704560.0 Ops/sec |
WeakMap get | 97679648.0 Ops/sec |
Symbol Property get | 153358800.0 Ops/sec |
CustomWeakMap set | 167226688.0 Ops/sec |
CustomWeakMap get | 173829632.0 Ops/sec |
This benchmark compares three different approaches to key-value data storage in JavaScript:
WeakMap:
WeakMap
is a collection of key/value pairs that allows only objects as keys. In a WeakMap
, the keys are "weakly referenced," meaning if there are no other references to a key object, it can be garbage collected.Symbol Property:
CustomWeakMap:
WeakMap
using regular property access on objects. The class uses a relation key to store associated values.WeakMap
, but the user has control over implementation and can optimize specific use cases.WeakMap
but slower than custom implementations at 153358800.0 operations per second.The results indicate that while WeakMap
provides significant advantages in memory management, it may not perform as well as the direct approaches (using symbols or custom implementations). If memory management and automatic cleanup are not as critical for the application's logic, the custom WeakMap
implementation and symbol properties offer competitive performance with the added advantage of flexibility in handling keys.
Other alternatives to consider for key-value data storage in JavaScript include using plain objects for simple mapping requirements, or third-party libraries such as Immutable.js
or Lodash
, which offer functional data structures that can provide performance benefits and extra functionality depending on your use case.