<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = [{
description: 'a',
myNumber: 123456789,
myBoolean: true,
}];
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = [MyObject];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Spread operator |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 2195070.5 Ops/sec |
Spread operator | 11772208.0 Ops/sec |
This benchmark tests the performance of two different ways to create a copy of an object in JavaScript:
_.cloneDeep(MyObject)
: This uses the cloneDeep
function from the Lodash library. Lodash is a popular JavaScript utility library that provides a wide range of functions for working with arrays, objects, and strings, among other things. The cloneDeep
function creates a deep copy of an object, meaning that it copies not only the top-level properties but also any nested objects within the original object.[...MyObject]
: This uses the spread operator (...
) to create a shallow copy of the object. A shallow copy means that the new object contains references to the same objects as the original object, so if there are nested objects, they will be shared between the two objects.Pros and Cons:
cloneDeep
:Other Considerations:
The choice between these two approaches depends on your specific needs. If you need a deep copy where changes to the copy won't affect the original, use _.cloneDeep
. If you only need a shallow copy and are comfortable with the potential for shared references, use the spread operator.
Alternatives:
There are other ways to create copies of objects in JavaScript:
Let me know if you have any other questions about this benchmark or JavaScript object copying in general!