<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var originalObject = {
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 copiedObject = null;
copiedObject = _.cloneDeep(originalObject);
copiedObject = structuredClone(originalObject);
copiedObject = JSON.parse(JSON.stringify(originalObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone | |
JSON.parse(JSON.stringify()) |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 1256382.0 Ops/sec |
Native structuredClone | 578351.6 Ops/sec |
JSON.parse(JSON.stringify()) | 1113485.6 Ops/sec |
Let's break down the benchmark and its various components.
Benchmark Definition
The provided JSON represents a JavaScript microbenchmark that tests the performance of three approaches: Lodash's cloneDeep
function, the native structuredClone
function, and the legacy JSON.parse(JSON.stringify())
method.
Options Compared
cloneDeep
function from the Lodash library to create a deep copy of the input object.structuredClone
function, which is introduced in ECMAScript 2020 (ES2020) as a part of the Web APIs specification.JSON.parse(JSON.stringify())
method to create a deep copy of the input object.Pros and Cons
Library: Lodash
Lodash is a popular JavaScript utility library that provides a comprehensive set of functions for tasks like array manipulation, object creation, and more. The cloneDeep
function is specifically designed to create deep copies of complex objects, which makes it an attractive option for this benchmark.
Native structuredClone Functionality
The native structuredClone
function is introduced in ECMAScript 2020 as a part of the Web APIs specification. It provides a standardized way to create deep copies of objects and arrays while preserving their original structure and semantics. The implementation details are specific to each browser engine, but the basic idea is to use a combination of object and array constructors to create a new, independent copy.
Other Alternatives
In addition to the options mentioned above, there are other approaches to creating deep copies in JavaScript:
for...of
loop with an iterator can be used to create a deep copy by pushing each object's properties into an array and then re-iterating over that array.Object.assign()
to merge objects, recursively cloning nested properties.slice()
to create a new array and then concatenating it with concat()
.However, these alternatives might not be as efficient or standardized as the options mentioned above.
Keep in mind that this is just an overview, and the best approach for your specific use case may depend on factors like performance requirements, browser support, and personal preference.