<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
var bob = {
name: "Bob",
age: 32,
lastName: "test",
local: {there:"there"},
test:{
test:{
test:"test"
}
}
};
function cloneObject(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var temp = obj.constructor(); // give temp the original obj's constructor
for (var key in obj) {
temp[key] = cloneObject(obj[key]);
}
return temp;
}
var bill = (cloneObject(bob));
var bill2 = (JSON.parse(JSON.stringify(bob)));
var deep = _.cloneDeep(bob);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
vanila | |
JSON.parse | |
lodash |
Test name | Executions per second |
---|---|
vanila | 1143883.2 Ops/sec |
JSON.parse | 246639.2 Ops/sec |
lodash | 135253.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark definition is provided in JSON format, which outlines two scripts: Script Preparation Code
and Html Preparation Code
. The Script Preparation Code
defines an object bob
with various properties, including nested objects. The Html Preparation Code
includes a reference to the Lodash library.
Options Compared
The benchmark compares three different approaches for cloning the bob
object:
cloneObject
that recursively clones the object using its constructor and properties.JSON.parse
method to clone the object by stringifying it, parsing it back as JSON, and then converting the resulting JSON string back to an object.cloneDeep
function to deep-clone the object.Pros and Cons of Each Approach
JSON
object.Library and Its Purpose
The Lodash library is used in the benchmark to provide a convenient and efficient way to perform deep cloning of complex objects.
Special JS Feature or Syntax
None mentioned in this specific benchmark.
Other Considerations
When testing benchmarking results, it's essential to consider factors such as:
Alternatives
Other approaches for cloning objects in JavaScript include:
Object.assign
method with a deep copy function (e.g., deepcopy
from the lodash
library).json-stringify-safe
or json-deep-clone
.Keep in mind that the performance difference between these approaches may be negligible for simple cloning tasks, but it's essential to consider factors like memory usage and overhead when choosing a method.