<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
var myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
let a = Object.assign({}, myObj)
let a = _.cloneDeep(myObj)
let a = JSON.parse(JSON.stringify(myObj))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
extend | |
cloneDeep | |
JSON.* |
Test name | Executions per second |
---|---|
extend | 4513933.5 Ops/sec |
cloneDeep | 1246358.2 Ops/sec |
JSON.* | 780179.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark measures the performance of three methods to create a copy of an object: Object.assign()
, _cloneDeep()
from the Lodash library, and JSON.parse(JSON.stringify())
.
Options Compared
Object.assign()
: This method creates a shallow copy of an object by iterating over its enumerable properties and assigning them to a new object.JSON.parse(JSON.stringify())
: This method serializes the original object as JSON string, then parses it back into an object, effectively creating a deep copy.Pros and Cons
Object.assign()
:_cloneDeep()
:JSON.parse(JSON.stringify())
:Object.assign()
for large objects due to JSON serialization overhead.Library and its Purpose
_cloneDeep()
is a specific function designed to recursively clone deep nested objects.Special JS Features/Syntax
None mentioned explicitly, but note that the Object.assign()
method was introduced in ECMAScript 2015 (ES6), and its behavior may vary across older browsers or environments.
Alternative Approaches
Other methods for creating object copies include:
for...in
loops to iterate over object properties and manually assign values.lodash.clone()
(an alias for _cloneDeep()
) or other deep cloning libraries.Keep in mind that the performance differences between these approaches might be negligible in most cases, but this benchmark can help identify potential bottlenecks in specific scenarios.