<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 = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 934400.3 Ops/sec |
Json clone | 825719.1 Ops/sec |
Let's dive into the world of MeasureThat.net and explore what's being tested in this benchmark.
Benchmark Overview
The benchmark compares two approaches to create a deep copy of an object: using the cloneDeep
function from Lodash and using the JSON.parse(JSON.stringify())
method. The test case creates a sample object MyObject
with nested properties, including objects and arrays.
Options Compared
Two options are compared:
cloneDeep
function from Lodash to create a deep copy of the object. Lodash is a utility library that provides functions for functional programming tasks.JSON.parse(JSON.stringify())
method, which converts the original object into a JSON string and then parses it back into an object.Pros and Cons
cloneDeep
due to the overhead of converting to JSON and parsing back.Library: Lodash
Lodash is a popular utility library that provides functions for functional programming tasks, such as array manipulation, object transformation, and more. The cloneDeep
function is part of this library and is specifically designed to create deep copies of objects.
Other Considerations
cloneDeep
, Lodash allocates new memory for the copied object, which can be beneficial if the original object is large and you want to avoid modifying it.Special JS Feature or Syntax
None mentioned in the provided benchmark definition.
Alternative Approaches
Other approaches to create deep copies of objects include:
Object.assign()
: This method creates a shallow copy of an object by copying its enumerable properties.Array.prototype.slice()
and JSON.stringify()
: This approach creates a deep copy of arrays, but may not work correctly with objects.cloneDeep
.Keep in mind that these alternative approaches might not offer the same level of performance or convenience as using Lodash's cloneDeep
function.