function objClone(obj) {
var index = 0,
keys = Object.keys(obj),
length = keys.length,
key,
result = {};
for (; index < length; index += 1) {
key = keys[index];
result[key] = obj[key];
}
return result;
}
var testObj = {
a: {
b: {
c: [1,2,4, {}, [4,2], {
d: 4,
e: {},
f: [4,5,2],
}]
}
}
};
objClone(testObj)
Object.assign({}, testObj);
Object.freeze(objClone)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
clone object manually | |
clone object native | |
freeze |
Test name | Executions per second |
---|---|
clone object manually | 2219568.8 Ops/sec |
clone object native | 2215845.5 Ops/sec |
freeze | 2707.9 Ops/sec |
Let's break down the provided JSON and benchmark results to understand what is being tested.
Benchmark Definition JSON
The JSON contains two main sections: Script Preparation Code
and Html Preparation Code
. The Script Preparation Code
section defines a JavaScript function objClone
that clones an object manually. The Html Preparation Code
section is empty, indicating no HTML-specific code needs to be executed before running the benchmark.
The Benchmark Definition
JSON also includes three test cases:
clone object manually
: This test case runs the objClone
function with the testObj
as input.clone object native
: This test case uses the built-in Object.assign()
method to clone the testObj
.freeze
: This test case freezes the result of the objClone
function using the Object.freeze()
method.Test Cases
Let's examine each test case:
objClone
) to clone an object. The pros of this approach are:Object.assign()
) provided by JavaScript. The pros of this approach are:objClone
function using Object.freeze()
. The pros of this approach are:Library/Functionality Used
The objClone
function uses a manual implementation to clone an object. This is not a built-in JavaScript library, but rather a custom function defined in the Script Preparation Code
.
Special JS Feature/Syntax
None of the test cases explicitly use any special JavaScript features or syntax beyond what's commonly used in modern JavaScript.
Other Alternatives
If you're looking for alternative approaches to cloning objects in JavaScript, consider using:
cloneDeep()
function: A popular library that provides a robust and efficient way to clone objects.However, keep in mind that these alternatives might not be suitable for every use case, especially when performance or control are critical factors.
In summary, the provided benchmark tests three different approaches to cloning objects: manual implementation (objClone
), built-in method (Object.assign()
), and freezing the result (Object.freeze()
). Each approach has its pros and cons, and choosing the right one depends on your specific use case and requirements.