<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = [];
for (let i=0; i<100000; i++) {MyObject.push({
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...'
}
})}
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone | |
JSON Parse |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 12.8 Ops/sec |
Native structuredClone | 12.3 Ops/sec |
JSON Parse | 16.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is testing three approaches to create a deep copy of an object:
cloneDeep
functionstructuredClone
API (introduced in Chrome 127)JSON.parse(JSON.stringify())
methodOptions Compared
cloneDeep
: a popular JavaScript library for functional programming, providing a way to create deep copies of objects.structuredClone
: a new feature introduced in Chrome 127 that allows creating deep copies of complex data structures, including objects and arrays.JSON.parse(JSON.stringify())
: a built-in JavaScript method that converts a value to a JSON string and then parses it back into an object. This method is not suitable for creating deep copies, as it only clones the top-level properties and does not recursively copy nested objects.Pros and Cons of Each Approach
cloneDeep
:structuredClone
:JSON.parse(JSON.stringify())
:Library and Purpose
Lodash's cloneDeep
is a popular JavaScript library that provides a way to create deep copies of objects. It recursively clones all nested properties and is widely used in the industry.
Special JS Feature or Syntax
The native structuredClone
API uses a new syntax called "structured clone" which was introduced in ECMAScript 2022. This feature allows creating deep copies of complex data structures, including objects and arrays, while preserving their original structure and relationships. The structuredClone
function is only available in Chrome 127 and later versions.
Other Alternatives
If you don't have access to Lodash or the native structuredClone
API, other alternatives for creating deep copies of objects include:
JSON.parse(JSON.stringify())
, but be aware that this method only creates a shallow copy).