<script src='https://cdn.jsdelivr.net/npm/object-assign-polyfill@0.1.0/index.min.js'></script>
<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 = _.clone(MyObject);
myCopy = Object.assign({}, MyObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 1418305.5 Ops/sec |
Json clone | 3028285.2 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
What is being tested?
The benchmark measures the performance of two approaches to create a deep copy of an object:
cloneDeep
function from the Lodash library, which recursively clones the entire object.Options compared
The two options being compared are:
Pros and Cons
Library usage
The Lodash library is used for the cloneDeep
function. It provides a convenient way to create deep copies of objects, as well as many other utility functions.
Special JavaScript feature or syntax
There is no specific special JavaScript feature or syntax being tested in this benchmark. Both approaches are standard JavaScript methods.
Other alternatives
If you need to create a deep copy of an object without using Lodash, you can implement your own recursive function:
function cloneDeep(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
const clone = Array.isArray(obj) ? [] : {};
for (const key in obj) {
clone[key] = cloneDeep(obj[key]);
}
return clone;
}
Alternatively, you can use a library like lodash
or json-stringify-safe
to create deep copies of objects.
Benchmark preparation code
The script preparation code defines two objects:
MyObject
: The original object with nested propertiesmyCopy
: The variable that will store the cloned copy of MyObject
The Html Preparation Code includes external scripts for Lodash and Object-assign-polyfill, as they are required for this benchmark.
Individual test cases
There are two test cases:
MyObject
using the cloneDeep
function from Lodash.MyObject
using the Object.assign
method.These test cases measure the performance of each approach under different conditions, including various browsers and devices.