<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'>
const _ = lodash
</script>
_.cloneDeep({ prop: { subprop: 'value' } })
const trueclone = (obj) => {
const cloned = Array.isArray(obj) ? [] : {}
const keys = Object.keys(obj)
const values = Object.values(obj)
const length = keys.length
for (let i = 0; i < length; i++) {
if (typeof values[i] === 'object') values[i] = trueclone(values[i])
cloned[keys[i]] = values[i]
}
return cloned
}
trueclone({ prop: { subprop: 'value' } })
structuredClone({ prop: { subprop: 'value' } })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash cloneDeep | |
my super deep cloner yeah | |
structuredClone |
Test name | Executions per second |
---|---|
lodash cloneDeep | 980598.2 Ops/sec |
my super deep cloner yeah | 846712.8 Ops/sec |
structuredClone | 403174.0 Ops/sec |
Let's break down the provided benchmark.
Overview
The benchmark is comparing three different approaches to create a deep clone of an object: Lodash's cloneDeep
, a custom implementation called "my super deep cloner", and the native JavaScript function structuredClone
.
Options Compared
cloneDeep
: This is a popular library for working with JSON data in JavaScript. cloneDeep
creates a deep clone of an object by recursively iterating over its properties and creating new objects for each level of nesting.structuredClone
: Introduced in ECMAScript 2020, structuredClone
is a built-in function that creates a deep clone of an object by recursively iterating over its properties.Pros and Cons
cloneDeep
:structuredClone
:Library and Purpose
Lodash is a popular utility library for JavaScript that provides a wide range of functions for working with data structures, such as arrays, objects, and functions. cloneDeep
is one of its most useful functions, allowing developers to create deep clones of complex data structures.
Special JS Feature or Syntax
There isn't any specific JavaScript feature or syntax mentioned in the benchmark. However, it's worth noting that structuredClone
uses a proprietary mechanism (not part of the ECMAScript standard) to clone objects, which might not be compatible with older browsers or environments.
Other Alternatives
If you need an alternative deep cloning library, some popular options include:
cloneDeep
function.Keep in mind that these alternatives might have different trade-offs and use cases compared to Lodash's cloneDeep
.