const set = new Set();
for (let i = 0; i < 10000; ++i) {
set.add(`key_${i}`);
}
const obj = {};
for (let i = 0; i < 10000; ++i) {
obj[`key_${i}`] = true;
}
const map = new Map();
for (let i = 0; i < 10000; ++i) {
map.set(`key_${i}`, true);
}
let result = 0;
for (let j = 0; j < 100; ++j) {
const clone = new Set(set);
}
console.log(result);
let result = 0;
for (let j = 0; j < 100; ++j) {
const clone = {obj};
}
console.log(result);
let result = 0;
for (let j = 0; j < 100; ++j) {
const clone = new Map(map);
}
console.log(result);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Object | |
Map |
Test name | Executions per second |
---|---|
Set | 87.7 Ops/sec |
Object | 3.7 Ops/sec |
Map | 13.5 Ops/sec |
The benchmark tests compare the performance of three different data structures in JavaScript: Set
, Object
, and Map
, specifically focusing on their cloning capabilities. Each data structure is instantiated and populated with the same keys, and the benchmark measures the performance of cloning these structures.
Set:
Set
by passing the existing Set
to its constructor.Object:
{...obj}
to create a shallow clone of the Object
.Map:
Map
by passing the existing Map
to its constructor.Set
and Map
.Set
, making it efficient.Set
, but generally offers better performance than Object
for large data sets.Set
, Map
, and Object
depends on the specific requirements of the application. Sets
are ideal for collections of unique items, Maps
are beneficial when order matters or when working with key-value pairs, while Objects
are suitable for simple data structures.Other alternatives for cloning objects might include:
Deep Copy Libraries: Libraries like lodash
provide methods such as _.cloneDeep()
which perform a deep copy, though they can be slower when clones contain nested structures.
JSON Methods: Using JSON.stringify()
and JSON.parse()
for cloning objects is another alternative, but it has limitations, such as not supporting functions or special data types (like Date
or undefined
).
Manual Cloning: Writing a custom cloning function can handle specific requirements (like cloning only certain properties) but increases complexity.
These alternatives provide different trade-offs in terms of performance, complexity, and fidelity to the original data structure.