<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = {color: "#BDBDBD", x: 506, y: 230.75};
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
structedClone (native) | |
JSON.parse |
Test name | Executions per second |
---|---|
lodash | 2466238.8 Ops/sec |
structedClone (native) | 936490.4 Ops/sec |
JSON.parse | 2559544.8 Ops/sec |
Overview
The provided benchmark measures the performance of three methods for creating a copy of an object in JavaScript: Lodash's cloneDeep
, Mozilla's structuredClone
(a native implementation), and JSON.parse(JSON.stringify(obj))
. The goal is to determine which method is the fastest.
Methods Compared
cloneDeep
: This method uses a recursive approach to create a deep copy of an object, which means it also copies nested objects.structuredClone
(native): This is a native implementation in JavaScript, introduced in ECMAScript 2022, that creates a shallow copy of an object by creating a new instance with the same value types and property names as the original object.JSON.parse(JSON.stringify(obj))
: This method uses JSON serialization to create a copy of an object. It serializes the object to a string using JSON.stringify
, then deserializes it back into an object using JSON.parse
.Pros and Cons
cloneDeep
:structuredClone
(native):JSON.parse(JSON.stringify(obj))
:NaN
, Infinity
).Library and Purpose
In this benchmark, Lodash is a popular JavaScript utility library that provides various functions for tasks like array manipulation, string manipulation, and more. The cloneDeep
function is part of Lodash's deep object manipulation module.
Special JS Features or Syntax
There are no special JS features or syntax used in these benchmarks. They focus on the performance comparison of three distinct methods for creating object copies.
Other Alternatives
If you need to create a copy of an object, other alternatives include:
Object.assign()
: Creates a shallow copy of an object by copying all own enumerable properties.Array.prototype.slice()
or Array.prototype.reduce()
: Can be used to create a shallow copy of an array (or an object that is converted to an array).Keep in mind that the choice of method depends on your specific use case, performance requirements, and personal preference.