<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...'
}
};
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-Clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 1927894.0 Ops/sec |
Native structuredClone | 744177.4 Ops/sec |
JSON-Clone | 1564719.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is tested?
The provided JSON represents three test cases:
cloneDeep
function, which creates a deep copy of an object.structuredClone
function in Firefox 111, which also creates a deep copy of an object. This is a relatively new feature introduced in recent versions of Firefox.JSON.stringify()
and JSON.parse()
functions to create a deep copy of an object.Options compared
The benchmark compares the performance of three different approaches:
cloneDeep
functionstructuredClone
function (only available in Firefox 111)JSON.stringify()
and JSON.parse()
functions to create a deep copyPros and Cons of each approach:
Library usage
The benchmark uses Lodash (version 4.17.5) as a library for the cloneDeep
function.
Special JS feature or syntax
None mentioned in this particular benchmark.
Other considerations
When choosing a method for deep copying objects, consider factors such as:
structuredClone
might be more efficient.Alternatives
If you're looking for alternative deep copying methods:
Object.assign()
with an object literal.Keep in mind that these alternatives might have different performance characteristics and compatibility issues compared to the methods tested in this benchmark.