var newArr = ['1', '2', '3', '4'];
const arrCopy = newArr.slice()
const arrCopy = [newArr]
const arrCopy = Array.from(newArr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Slice | |
Spread | |
Array.from |
Test name | Executions per second |
---|---|
Slice | 21226136.0 Ops/sec |
Spread | 25811414.0 Ops/sec |
Array.from | 10139793.0 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance of creating shallow copies of an array in JavaScript using three different methods: slice()
, spread operator (...
), and Array.from()
.
Methods Compared
...
): This method creates a new array by spreading the elements of the original array into a new array.Pros and Cons
...
):slice()
for very large arrays.Library Usage
None of the provided methods use any external libraries.
Special JavaScript Features/Syntax
The test cases use the following special JavaScript features/syntax:
...
): This feature is only available in JavaScript version 13+ (or later).Other Alternatives
If you need to create shallow copies of arrays in JavaScript, there are two alternative methods:
Example:
const arrCopy = [];
for (let i = 0; i < newArr.length; i++) {
arrCopy.push(newArr[i]);
}
or
const arrCopy = newArr.map((element) => {
// You can add additional logic here if needed
return element;
});
Keep in mind that these alternatives may not be as efficient or concise as the methods used in the benchmark, but they can be useful in certain situations.