<!--your preparation HTML code goes here-->
const array = Array.from({ length: 128000 }, (_, i) => { return { i } })
const copy = [array];
const copy = array.slice();
const copy = Array.from(array);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
Slice | |
Array.from |
Test name | Executions per second |
---|---|
Spread | 173.5 Ops/sec |
Slice | 2191.4 Ops/sec |
Array.from | 151.3 Ops/sec |
The benchmark "Array clone (spread vs slice vs array.from)" evaluates the performance of three different techniques for cloning an array in JavaScript. Below are the methods compared, their pros and cons, and other considerations.
Spread Operator ([...]
)
const copy = [...array];
Array.prototype.slice()
const copy = array.slice();
slice()
method returns a shallow copy of a portion of an array into a new array object. When called without any arguments, it returns the complete array.Array.from()
const copy = Array.from(array);
Array.from()
creates a new array instance from an array-like or iterable object. In this case, it converts the array
to a new array.The executed benchmarks provided the following performance results, measured in Executions Per Second:
According to the results, Array.from()
performed the best, closely followed by slice()
. The spread operator was the slowest in this set of benchmarks. This could be due to how the JavaScript engine optimizes for these operations; certain implementations may be able to better optimize for the built-in Array.from()
and slice()
compared to the syntactic spread operator.
JSON.parse(JSON.stringify(array))
or external libraries) should be considered.const copy = JSON.parse(JSON.stringify(array));
creates a deep copy but comes with serialization limitations (e.g., does not handle functions, prototypes, or special objects like Date
)._.cloneDeep(value)
, which can be beneficial when working with complex nested structures.In summary, the benchmark presents a comparative evaluation of cloning techniques in JavaScript and sheds light on their performance characteristics, pros, and cons to guide developers in choosing the most suitable method for their specific use cases.