<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'.repeat(300000),
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 | 735118.0 Ops/sec |
Json clone | 79.4 Ops/sec |
Let's break down the benchmark and explain what's being tested.
What's being tested: The benchmark is comparing two approaches to create a deep copy of a large object:
_.cloneDeep(MyObject)
using LodashJSON.parse(JSON.stringify(MyObject))
These two methods are used to duplicate an object, which includes arrays and objects as properties.
Options compared:
JSON.parse(JSON.stringify())
: A built-in JavaScript method for cloning objects.Other considerations:
MyObject
) with 300,000 repeated strings (myNumber
), nested objects (jayson
), and other properties. This helps to stress the cloning mechanisms and demonstrate their performance differences.Html Preparation Code
includes a link to Lodash, which is necessary for the first test case.Library used:
Lodash (version 4.17.5) is used in the benchmarking process. It provides the _.cloneDeep()
function, which creates a deep copy of an object.
Special JS feature or syntax: None mentioned in this specific benchmark.
Benchmark preparation code:
The code prepares two objects:
MyObject
: A nested object with various properties, including arrays and strings.myCopy
: An empty variable that will receive the cloned object (or a new copy).Individual test cases:
Two test cases are defined:
Lodash cloneDeep
: Creates a deep copy of MyObject
using Lodash's _.cloneDeep()
function.Json clone
: Creates a deep copy of MyObject
using the native JSON.parse(JSON.stringify())
method.Latest benchmark result:
The latest results show that:
Keep in mind that these results are specific to this particular benchmark and environment. The actual performance differences between these methods may vary depending on other factors, such as the specific use case, data size, and JavaScript engine being used.