<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
<script src='https://unpkg.com/clone@2.1.2/clone.js'></script>
var o = {
a: {
b: 1,
c: 2,
d: 3,
j: {
k: [1,2,3],
l: [4,5,6]
},
},
e: [1,2,3,4,5,6],
f: 1,
g: {
h: 1,
}
}
const a = _.cloneDeep(o)
const a = clone(o)
const a = JSON.parse(JSON.stringify(o))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Clone | |
JSON |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 139686.7 Ops/sec |
Clone | 77917.9 Ops/sec |
JSON | 297258.4 Ops/sec |
What is being tested?
The provided benchmark measures the performance of different approaches for creating a shallow copy of an object in JavaScript.
Options compared:
cloneDeep
: A function that creates a deep copy of an object, recursively cloning all nested objects and arrays.JSON.parse(JSON.stringify())
: A method that converts a JSON string back to a JavaScript object, which can be used to create a shallow copy of an object.clone
: A function that creates a shallow copy of an object, cloning only the top-level properties and not recursively cloning nested objects or arrays.{ ... }
): A method that creates a new object by spreading the properties of an existing object into it.Object.assign()
: A method that copies all enumerable own properties from one or more source objects to a target object.Object.assign()
: A method that copies all enumerable own properties from one or more source objects to a target object.Pros and Cons of each approach:
cloneDeep
:JSON.parse(JSON.stringify())
:clone
:cloneDeep
, as it only clones top-level properties.{ ... }
) and ES6 Object.assign()
:Object.assign()
:Library and purpose descriptions:
Special JS features or syntax:
None mentioned in the benchmark definition. However, it's worth noting that the use of let
and const
declarations (e.g., var o = ...
) is specific to JavaScript 6+ versions.
Other alternatives:
Keep in mind that the choice of implementation will depend on the specific requirements of your project, such as performance, code readability, and data integrity.