<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var arr = new Array(100000000).fill(0);
_.clone(arr);
structuredClone(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
structuredClone |
Test name | Executions per second |
---|---|
Lodash | 0.8 Ops/sec |
structuredClone | 0.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark measures the performance of two methods for cloning an object in JavaScript: lodash.clone
and structuredClone
.
Options Compared
Two options are compared:
_.clone()
method from the Lodash library, which is a utility library that provides a wide range of functions for functional programming.structuredClone()
function, which is a native JavaScript function introduced in ECMAScript 2020 (ES2020) as part of the WebAssembly specification. It allows cloning objects without creating new objects or allocating memory.Pros and Cons
Here are some pros and cons for each approach:
Structured Clone
Pros:
Cons:
Library and Syntax
The structuredClone()
function is part of the ECMAScript standard, which means it's a native JavaScript function. It was introduced as part of the WebAssembly specification to provide a way to clone objects without creating new objects or allocating memory.
There is no special syntax required to use the structuredClone()
function. You can simply call it on an object, like this:
const obj = { foo: 'bar' };
const clonedObj = structuredClone(obj);
Alternative Approaches
Other alternatives for cloning objects in JavaScript include:
structuredClone()
function.JSON.parse(JSON.stringify(obj))
but still may not outperform structuredClone()
for large objects.Keep in mind that these alternatives have different trade-offs and may not offer the same level of performance or functionality as the structuredClone()
function.