<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 = {MyObject};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 706060.8 Ops/sec |
Json clone | 4770415.0 Ops/sec |
Benchmark Overview
The provided benchmark compares two approaches to create a deep copy of an object in JavaScript: using the _.cloneDeep()
method from Lodash and using the spread operator (...
) on arrays.
Options Compared
Two options are compared:
_.cloneDeep()
method from Lodash, which creates a deep copy of an object by recursively cloning all its properties....
) to create a shallow copy of an array, and then iteratively clones each property of the object using JSON.parse().Pros and Cons
Pros:
Cons:
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for common tasks such as array manipulation, string manipulation, and object manipulation. The _.cloneDeep()
method is specifically designed to create deep copies of objects, making it a convenient choice for this benchmark.
Special JS Feature/Syntax: Spread Operator
The spread operator (...
) was introduced in ECMAScript 2015 (ES6) as a way to expand an array into individual elements or merge two arrays into one. This feature is used in the "Json clone" approach to create a shallow copy of the object.
Benchmark Preparation Code Explanation
The script preparation code defines a JavaScript object MyObject
with several properties, including nested objects and arrays. The myCopy
variable is initialized to null
. The benchmark definition scripts use either Lodash's _.cloneDeep()
method or the spread operator (...
) to create a copy of MyObject
.
Alternative Approaches
Other approaches that could be used to compare in this benchmark include:
JSON.parse()
and JSON.stringify()
methods together to create a deep copy.These alternative approaches would require modifications to the benchmark script preparation code and test cases.