<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
window.obj = { foo: 'some string', bar: 'another', subObj: { hey: 'you', what: 'are you doing' } }
const objClone = _.cloneDeep(window.obj);
const objClone = JSON.parse(JSON.stringify(window.obj));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash deep clone | |
JSON.stringfy |
Test name | Executions per second |
---|---|
Lodash deep clone | 1313123.9 Ops/sec |
JSON.stringfy | 987889.2 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for creating a deep clone of an object in JavaScript: using Lodash's cloneDeep
function and using the JSON.parse(JSON.stringify())
method. The goal is to determine which approach is faster.
Options Compared
cloneDeep
function: This is a popular utility function in Lodash that creates a deep clone of an object. It recursively traverses the object graph, creating new objects for each nested property.JSON.parse(JSON.stringify())
method: This method uses JSON serialization and deserialization to create a deep clone of an object. The JSON.stringify()
method converts the object into a JSON string, which can then be parsed back into a JavaScript object using JSON.parse()
.Pros and Cons
cloneDeep
function:JSON.parse(JSON.stringify())
method:cloneDeep
function, as it involves serialization and deserialization steps.Library and Purpose
The benchmark uses the Lodash library, which is a popular collection of utility functions for JavaScript. The cloneDeep
function is specifically designed to create deep clones of objects, making it a useful tool for many use cases, such as data transformation or mocking.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark.
Other Alternatives
If you need to create a deep clone of an object without using Lodash, you can also consider other libraries like:
lodash-es
: A lightweight alternative to Lodash that uses modern JavaScript features.immutability-helper
: A library specifically designed for creating immutable data structures in JavaScript.For non-library solutions, you can use techniques like recursively traversing the object graph and creating new objects for each nested property. However, this approach may be slower and more cumbersome than using a dedicated library or function like Lodash's cloneDeep
.
In summary, the benchmark compares two approaches for creating deep clones of objects: using Lodash's cloneDeep
function versus the JSON.parse(JSON.stringify())
method. While both approaches have their pros and cons, Lodash's cloneDeep
function is generally faster and more efficient, but adds an external dependency.