<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/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...'
}
};
const kitchenSink = {
set: new Set([1, 3, 3]),
map: new Map([[1, 2]]),
regex: /foo/,
error: new Error('Hello!')
}
MyObject.kitchen = kitchenSink;
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 275988.7 Ops/sec |
Native structuredClone | 220294.1 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Definition
The test measures the performance of two approaches to create a deep copy of an object: lodash.cloneDeep
and the native structuredClone
function.
Options Compared
Two options are compared:
cloneDeep
, which creates a deep copy of an object.structuredClone
function in modern browsers and Node.js environments.Pros and Cons
Here's a brief overview of each approach:
structuredClone
, and its performance can vary depending on the specific use case.Library and Its Purpose
The lodash
library is a popular JavaScript utility library that provides various functions for tasks like array manipulation, object manipulation, and more. The cloneDeep
function is specifically designed to create deep copies of objects, which can be useful in scenarios where you need to modify a copy of an original object without affecting the original.
Special JS Feature or Syntax
The test uses the structuredClone
function, which was introduced in ECMAScript 2022 (ES12). This function creates a deep clone of an object, including its properties and their values. It's designed to work with a wide range of data types, including arrays, objects, and more.
Other Considerations
When choosing between cloneDeep
and structuredClone
, consider the following:
structuredClone
, use cloneDeep
.structuredClone
might be a better choice.Alternatives
If structuredClone
is not available or not suitable for your use case, you can consider alternative deep cloning libraries like:
immer
: A popular library for creating immutable objects that supports deep copying.lodash.clone
: Another option from the Lodash family that creates a shallow copy of an object.