const arr = [1,2,3,4,5]
const newArr = arr.map(e=>e)
const arr = [1,2,3,4,5]
const newArr = Array.from(arr)
const arr = [1,2,3,4,5]
let newArr = [];
for(let i = 0; i < arr.length; i++) {
newArr[i] = arr[i];
}
const arr = [1,2,3,4,5]
let newArr = []
arr.forEach(e => {
newArr.push(e)
})
const arr = [1,2,3,4,5]
const newArr = arr.slice()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
array.from | |
for loop | |
foreach | |
slice |
Test name | Executions per second |
---|---|
map | 33293160.0 Ops/sec |
array.from | 10837964.0 Ops/sec |
for loop | 43802840.0 Ops/sec |
foreach | 36621396.0 Ops/sec |
slice | 46124496.0 Ops/sec |
I'll break down the test cases and provide an explanation of what's being tested, the pros and cons of each approach, and other considerations.
The benchmark measures the speed of different JavaScript methods for creating a new array from an existing one:
map()
: Creates a new array with the results of applying a provided function to every element in the original array.Array.from()
: Creates a new array populated from an array-like object.for
loop: Iterates over each element in the original array and assigns it to a new array.forEach()
with push()
: Iterates over each element in the original array and pushes it onto a new array.Options Compared
The benchmark compares these four methods for creating a new array:
for
loop: A low-level, manual approach that can be fast, but requires more code and is less readable.forEach()
with push()
: A combination of two methods: iterating over the array using forEach()
, which is relatively efficient, and pushing elements onto a new array using push()
. This method may have performance characteristics similar to map()
.Pros and Cons
from()
method.for
loop:forEach()
with push()
:map()
, uses a familiar pattern (forEach followed by an array operation).push()
, which may not be as efficient as other methods.Other Considerations
Array.from()
method can work with various types of data, including arrays and objects. However, the benchmark does not test this aspect, only array-like objects.map()
method involves a function call for each element in the original array, which may incur additional overhead compared to other methods.Alternatives
If you're looking for alternative methods, consider:
reduce()
: Can be used to create an array from a single value (e.g., [...Array(5).keys()]
)....
): Can be used to spread elements of one array into another ([...arr]
).Note that the performance characteristics of these alternatives may differ from those mentioned above.
In summary, the benchmark provides a concise comparison of four common methods for creating new arrays in JavaScript. Understanding the pros and cons of each approach can help developers choose the most suitable method for their use case.