<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var MyObject = {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 123456789,
myBoolean: true,
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...'
}
};
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash cloneDeep | |
JSON.parse(JSON.stringify()) |
Test name | Executions per second |
---|---|
lodash cloneDeep | 349532.4 Ops/sec |
JSON.parse(JSON.stringify()) | 169686.5 Ops/sec |
Let's break down the benchmark and its results.
What is being tested?
The provided JSON represents a JavaScript microbenchmarking test created on MeasureThat.net. The test compares two methods for creating a deep copy of an object:
_.cloneDeep
from the Lodash library.JSON.parse(JSON.stringify())
.These two approaches are compared to determine which one is faster and more efficient.
Options being compared:
The two options being tested are:
A) Using _.cloneDeep
from the Lodash library, which is a utility function that creates a deep copy of an object.
B) Using JSON.parse(JSON.stringify())
, which parses a JSON string and returns the equivalent JavaScript object. However, this approach does not create a true copy of the object; it only recreates the object with the same properties.
Pros and Cons:
_.cloneDeep (Lodash)
Pros:
Cons:
JSON.parse(JSON.stringify())
Pros:
Cons:
Other considerations:
cloneDeep
.JSON.parse(JSON.stringify())
assumes that the input object is in a format that can be safely parsed by JSON.Library and its purpose:
The Lodash library (specifically, the cloneDeep
function) is a popular JavaScript utility library that provides various functions for working with data structures, such as arrays, objects, and more. The cloneDeep
function creates a deep copy of an object, which can be useful in many scenarios where you need to work with independent copies of complex data.
Special JS feature or syntax:
There are no special JavaScript features or syntax used in this benchmark. Both methods rely on standard JavaScript language constructs and libraries (Lodash).
Now that we've analyzed the benchmark, let's take a look at some alternative approaches for creating deep copies of objects: