<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.20/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 | 1986753.4 Ops/sec |
JSON.stringfy | 1775136.5 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of two approaches for creating a deep clone of an object: Lodash's cloneDeep
function and JSON stringification using JSON.parse(JSON.stringify())
.
Options Being Compared
There are two options being compared:
cloneDeep
function: This is a utility function from the Lodash library that creates a deep copy of an object.JSON.parse(JSON.stringify())
: This approach serializes the original object to a JSON string, and then parses the resulting string back into an object.Pros and Cons
cloneDeep
function:JSON.parse(JSON.stringify())
:Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, object manipulation, and string manipulation. The cloneDeep
function is one of the many utilities provided by Lodash, designed to create deep copies of objects.
Special JS Feature/Syntax
There doesn't appear to be any special JavaScript features or syntax being used in this benchmark.
Other Alternatives
If you need a faster alternative to JSON.parse(JSON.stringify())
, you might consider using:
Array.prototype.slice()
to create an array copy of the object's values, and then parse the resulting array into an object using JSON.parse()
.Keep in mind that these alternatives may not be as convenient or efficient as Lodash's cloneDeep
function, but they can provide a good starting point for customizing the cloning process to suit your specific needs.