const set = new Set();
for (let i = 0; i < 1000; ++i) {
set.add(`key_${i}`);
}
let result = 0;
for (let j = 0; j < 100; ++j) {
const clone = new Set(set);
for (let k = -500; k < 500; ++k) {
result += clone.has(`key_${k}`);
}
}
console.log(result);
const obj = {};
for (let i = 0; i < 1000; ++i) {
obj[`key_${i}`] = true;
}
let result = 0;
for (let j = 0; j < 100; ++j) {
const clone = {obj};
for (let k = -500; k < 500; ++k) {
result += clone.hasOwnProperty(`key_${k}`);
}
}
console.log(result);
const map = new Map();
for (let i = 0; i < 1000; ++i) {
map.set(`key_${i}`, true);
}
let result = 0;
for (let j = 0; j < 100; ++j) {
const clone = new Map(map);
for (let k = -500; k < 500; ++k) {
result += clone.get(`key_${k}`);
}
}
console.log(result);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Object | |
Map |
Test name | Executions per second |
---|---|
Set | 298.2 Ops/sec |
Object | 48.3 Ops/sec |
Map | 148.5 Ops/sec |
This benchmark compares the performance of three different data structures (Set
, Object
, and Map
) when performing similar tasks involving cloning and membership checking.
Here's a breakdown:
Objective: The benchmark aims to measure how efficiently each data structure can create clones and check for the existence of keys within those clones.
Test Setup:
key_0
to key_999
).key_-500
to key_499
) exist within the clone using either has()
(for Set
), hasOwnProperty()
(for Object
), or get()
(for Map
).Options Compared:
Pros/Cons & Considerations:
Data Structure | Pros | Cons | Other Considerations |
---|---|---|---|
Set | Fast has() operation, efficient for uniqueness checks. |
Doesn't support additional data types as values (just boolean). | Not ideal for complex key-value relationships or when order matters. |
Object | Flexible, allows dynamic property addition. | Can be slow for large datasets, potential performance issues with numerous property accesses. | Use hasOwnProperty() to accurately check for keys. |
Map | Excellent performance for large datasets, supports various data types as keys and values, maintains insertion order. | More complex syntax than Object . |
Best choice when you need key-value pairs with diverse data types and efficient retrieval. |
_.cloneDeep()
) or Underscore.js for more robust cloning operations if you need finer control over the cloning process.Let me know if you have any other questions!