<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var o = {
a: {
b: 1,
c: 2,
d: 3,
j: {
k: [1,2,3],
l: [4,5,6]
},
},
e: [1,2,3,4,5,6],
f: 1,
g: {
h: 1,
}
}
const a = _.cloneDeep(o)
const a = JSON.parse(JSON.stringify(o))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Stringify |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 655539.2 Ops/sec |
Stringify | 1630170.6 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of two approaches: using Lodash's cloneDeep
function to create a deep copy of an object, and using JSON stringification and parsing to achieve the same result.
Options Compared
Two options are compared:
cloneDeep
function to create a deep copy of the input object o
. Lodash is a utility library that provides various functions for tasks like array manipulation, object creation, and more.o
into a JSON string using JSON.stringify(o)
, and then parsing (converting back to an object) the resulting string using JSON.parse(JSON.stringify(o))
. This method is often used for serializing and deserializing data in JavaScript applications.Pros and Cons of Each Approach
Library: Lodash
Lodash is a popular utility library for JavaScript that provides various functions for tasks like array manipulation, object creation, and more. In this benchmark, Lodash's cloneDeep
function is used to create a deep copy of an object.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark. The focus is on comparing the performance of two different approaches: using a library (Lodash) versus a built-in method (JSON.stringify()
and JSON.parse()
).
Other Alternatives
If you're looking for alternative methods to create deep copies of objects, some other options include:
{...o}
) to create a shallow copy of an object.Object.assign()
to create a shallow copy of an object.Array.prototype.slice()
to create a shallow copy of an array.Keep in mind that these alternatives may not provide the same level of functionality as Lodash's cloneDeep
function, which is designed specifically for creating deep copies of objects and arrays.