<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 stringify/parse |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 1932494.9 Ops/sec |
Native structuredClone | 1105791.9 Ops/sec |
JSON stringify/parse | 1815978.5 Ops/sec |
Overview
The provided JSON represents a JavaScript microbenchmark on MeasureThat.net, where users can compare the performance of different approaches to create a deep copy of an object. The benchmark tests three methods: Lodash's cloneDeep
function, Mozilla's native structuredClone
function, and the traditional method using JSON.stringify
and JSON.parse
.
Options compared
The three options being compared are:
JSON.stringify
to serialize the object and then parses it back into a new object.Pros and Cons
Library usage
The benchmark uses the lodash
library, which provides the cloneDeep
function. The script preparation code includes a script tag that loads the lodash.min.js
file from a CDN.
Special JS feature/syntax
There is no special JavaScript feature or syntax being used in this benchmark.
Other alternatives
If you're looking for alternative deep copy methods, some options include:
Keep in mind that these alternatives may not provide deep copies, and some may have performance implications depending on the use case.