<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/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...'
}
};
var myCopy = null;
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = structuredClone(MyObject);
myCopy = _.cloneDeep(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone | |
_.cloneDeep |
Test name | Executions per second |
---|---|
JSON.stringify | 555021.9 Ops/sec |
structuredClone | 285111.2 Ops/sec |
_.cloneDeep | 861007.4 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided JSON represents a benchmark that compares the performance of three different methods for creating deep copies of objects: JSON.stringify
, structuredClone
, and _cloneDeep
from the Lodash library.
Tested Options
The benchmark tests the execution speed of each method in creating deep copies of an object (MyObject
). The options being compared are:
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Library and Its Purpose
The structuredClone
method is a modern JavaScript function introduced in ECMAScript 2020 (ES10). It's designed to create shallow clones of objects, with the intention of eventually supporting deep cloning. The _cloneDeep
function from Lodash provides a more robust implementation for creating deep copies.
Special JS Feature or Syntax
None mentioned in this benchmark.
Other Considerations
When choosing between these methods, consider the following:
JSON.stringify
might be a safer choice.structuredClone
is likely the best option._cloneDeep
provides a convenient and efficient solution.Alternatives
If you don't want to use Lodash or prefer not to rely on modern JavaScript features, you can consider alternative methods for creating deep copies:
structuredClone
, this method can be used to create shallow clones of arrays.However, these alternatives may not be as efficient or reliable as structuredClone
and _cloneDeep
.