<script src="https://cdn.jsdelivr.net/npm/lodash@1.3.1/lodash.min.js"></script>
var items = [ Array(10000).keys() ].map( i => { return { bar: "foo" } });
_.cloneDeep(items);
JSON.parse(JSON.stringify(items));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
JSON parse/stringify |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 13.3 Ops/sec |
JSON parse/stringify | 720.5 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition
The benchmark is designed to compare two approaches for deep cloning an array of objects: _.cloneDeep
from Lodash and JSON.parse(JSON.stringify(items))
.
Options Compared
JSON.stringify
, which converts it to a string, and then parses that string back into an object using JSON.parse
. This can lead to issues with circular references.Pros and Cons
Library
The benchmark uses the Lodash library, specifically version 1.3.1, for its cloneDeep
function. Lodash is a popular utility library that provides a set of helper functions for common tasks, such as array manipulation, object creation, and more.
Special JS Feature or Syntax
There isn't any specific JavaScript feature or syntax mentioned in the benchmark definition or individual test cases. However, it's worth noting that some older browsers may not support modern JavaScript features like let
and const
, which are used extensively in Lodash code.
Other Alternatives
If you want to explore alternative approaches for deep cloning objects, here are a few options:
.slice()
method: You can use the .slice()
method on arrays or the Object.assign()
method on objects to create shallow clones.JSON.parse(JSON.stringify())
without Lodash: Without using Lodash, you can still achieve deep cloning by serializing the object and then parsing it back into an object, as shown in the benchmark definition.Keep in mind that each approach has its trade-offs, and the best choice depends on your specific use case and performance requirements.