function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
const clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
var n = {foo: 'bar', hello: [{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'}]};
while (n.length < 1000) {
n = deepClone(n);
}
var n = {foo: 'bar', hello: [{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'}]};
while(n.length < 1000) {
n = JSON.parse(JSON.stringify(n))
}
var n = {foo: 'bar', hello: [{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'}]};
while(n.length < 1000) {
n = Object.assign({}, n);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
deepclone | |
JSON Parse | |
Object.assign |
Test name | Executions per second |
---|---|
deepclone | 167270352.0 Ops/sec |
JSON Parse | 120818824.0 Ops/sec |
Object.assign | 166235760.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested in this benchmark.
Benchmark Definition
The test is designed to compare three approaches for creating a new object reference:
Object.assign()
deepClone()
)The benchmark aims to measure which approach creates the most efficient and scalable way to create a large number of objects.
Options being compared
The options being compared are:
Object.assign()
: A method that creates a new object by copying properties from an existing object.deepClone()
): A recursive function that creates a deep copy of an object.Pros and Cons
Here's a brief overview of each approach:
Object.assign()
:Object.assign()
due to the overhead of parsing the JSON string.deepClone()
):Library usage
The JSON.parse()
function uses the built-in JSON
library in JavaScript. This library provides methods for parsing JSON data from strings to JavaScript objects.
Special JS feature or syntax
There are no special JS features or syntaxes used in this benchmark that would require additional explanation.
Other alternatives
If you're looking for alternative approaches, consider:
JSON.parse()
method with a custom parser to handle complex data structures.However, keep in mind that these alternatives may introduce additional overhead and complexity compared to the original benchmark.
Benchmark result interpretation
The latest benchmark results show that Object.assign()
is the fastest approach, followed closely by JSON string parsing and then deep cloning using the custom deepClone()
function. This suggests that for this specific use case, Object.assign()
is the most efficient way to create a new object reference.