<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
window.dater = {
name: 'test',
arr: [1, 2, 3, 4, 5],
innerObj: {
name: 'Test Inner',
innerArr: [2, 4, 5, 6],
isDeleted: false,
},
sigh: true,
};
const res = JSON.parse(JSON.stringify(window.dater))
const result = _.cloneDeep(window.dater)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON | |
clone deep |
Test name | Executions per second |
---|---|
JSON | 1208402.1 Ops/sec |
clone deep | 793943.1 Ops/sec |
The provided benchmark tests two approaches for deep cloning a JavaScript object: using the JSON serialization method and using the Lodash library's cloneDeep
function. Below, we'll break down the options being compared, their pros and cons, and considerations for software engineers.
JSON Parse-Stringify Method
const res = JSON.parse(JSON.stringify(window.dater));
JSON.stringify()
and then immediately parse that string back into a JavaScript object using JSON.parse()
. This effectively creates a deep clone of the original object.Lodash Clone Deep Method
const result = _.cloneDeep(window.dater);
_.cloneDeep()
function can handle various types of objects, including those containing nested objects, arrays, and other JavaScript data structures.undefined
, and symbols. It also cannot handle circular references.Date
and RegExp
will be converted to their JSON equivalents (e.g., Date
to string) and lose their type.cloneDeep()
can handle a broader range of data types (functions, dates, special objects) and does not throw errors for circular references.Beyond the methods tested here, there are other strategies for deep cloning objects in JavaScript:
structuredClone()
method are available in modern browsers, which offer a standardized way to deep clone objects, including complex data types such as Map, Set, and all built-in types.By considering these methods and their trade-offs, software engineers can choose the most appropriate deep cloning strategy for their specific use case.