<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
const myObject = {
"event": "preferences_changed",
"data": {
"preferences": "[{\"user_id\":\"ыпукнунукр\",\"category\":\"direct_channel_show\",\"name\":\"фвыфпуцкнкнуцк\",\"value\":\"true\"},{\"user_id\":\"смчсмчсмсмчсмчм\",\"category\":\"channel_open_time\",\"name\":\"аываываываыва\",\"value\":\"1740485407949\"}]"
},
"broadcast": {
"omit_users": null,
"user_id": "фывфыввфывфывфывфыв",
"channel_id": "",
"team_id": "",
"connection_id": "",
"omit_connection_id": ""
},
"seq": 2
}
myCopy = _.cloneDeep(myObject);
myCopy = JSON.parse(JSON.stringify(myObject));
myCopy = structuredClone(myObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash CloneDeep | |
Json Clone | |
structured Clone |
Test name | Executions per second |
---|---|
Lodash CloneDeep | 549017.4 Ops/sec |
Json Clone | 320514.2 Ops/sec |
structured Clone | 221240.1 Ops/sec |
The benchmark defined in the JSON compares three different methods for deep cloning a JavaScript object. The three methods being evaluated are:
Lodash cloneDeep
: A utility function provided by the Lodash library for creating a deep clone of an object, which means creating a new object that is a copy of the original object, including nested objects.
JSON serialize/deserialize: This method involves converting an object to a JSON string and then parsing it back into a new object. This is often used as a quick way to deep clone objects, although it has limitations.
Structured Clone: This is a built-in JavaScript feature (available in modern browsers) that provides a way to create a deep clone of an object that can handle more complex data types, such as dates, maps, sets, and more.
Map
, Set
, Date
).Date
, Blob
, File
, Map
, Set
, and others.According to the provided benchmark results:
When choosing between these methods, developers should weigh their specific use case requirements such as:
Other alternatives not mentioned in the benchmark could include:
Ultimately, the best method for deep cloning objects in JavaScript depends on the specific scenarios and application requirements, such as performance, compatibility, and ease of use. Selecting the suitable method requires careful consideration of the trade-offs presented by each approach.