<script src='https://unpkg.com/klona@2.0.6/json/index.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/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...'
},
array: [
1, 2, 3,
{
one: [2, 3, 4]
}
]
};
var myCopy = null;
myCopy = structuredClone(MyObject);
myCopy = klona.klona(MyObject);
myCopy = _.cloneDeep(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native structuredClone | |
Klona | |
Lodash.cloneDeep |
Test name | Executions per second |
---|---|
Native structuredClone | 555290.8 Ops/sec |
Klona | 4019289.5 Ops/sec |
Lodash.cloneDeep | 788062.7 Ops/sec |
The provided benchmark is designed to compare the performance of three different methods for creating deep copies of a JavaScript object: structuredClone
, klona
, and lodash.cloneDeep
. Let's break down the benchmark and discuss the pros and cons of each approach, as well as other relevant considerations.
Native structuredClone:
myCopy = structuredClone(MyObject);
structuredClone
is a built-in JavaScript function that creates a deep copy of the provided object. It supports various data types such as objects, arrays, and even complex types like Dates and Map/Set collections.Klona:
myCopy = klona.klona(MyObject);
Klona
is a lightweight JavaScript library designed to create deep copies of objects. It aims to handle a wider variety of data types while maintaining performance. The version used here is 2.0.6
.Lodash.cloneDeep:
myCopy = _.cloneDeep(MyObject);
_.cloneDeep()
creates a deep copy of the value, handling complex structures and references.Based on the latest benchmark results, the performance was as follows:
Native structuredClone:
Klona:
Lodash.cloneDeep:
Choosing an Approach: When deciding which method to use, consider the specific requirements of your application. If performance is critical for deep copying, Klona might be the best choice based on benchmark results. If you need the most compatibility and simplicity, the native structuredClone could be sufficient, especially if you are sure about the object's complexity.
Alternatives: Other alternatives exist for deep copying objects, including using JSON serialization (e.g., JSON.parse(JSON.stringify(obj))
), although this has limitations such as not handling functions or special object types. Another alternative could be using the spread operator ({ ...obj }
) for shallow copying, but that wouldn't suffice for deep copies.
Given these insights, software engineers can make informed decisions on object copying methods based on performance needs and project requirements.