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()
const arr = [1,2,3,4,5]
const newArr = [ arr ]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
array.from | |
for loop | |
foreach | |
slice | |
spread |
Test name | Executions per second |
---|---|
map | 30028442.0 Ops/sec |
array.from | 3966581.5 Ops/sec |
for loop | 22481798.0 Ops/sec |
foreach | 23217018.0 Ops/sec |
slice | 59442456.0 Ops/sec |
spread | 38830696.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided JSON defines a benchmark that compares the performance of six different methods for creating a new array: map
, array.from
, for loop
, foreach
, slice
, and spread
. The test cases are identical, with the only difference being the method used to create the new array.
What is tested?
The benchmark tests the execution speed of each method on an array of five elements. The methods are compared in terms of their performance, measured in executions per second (ExecutionsPerSecond).
Options Compared
map()
: Creates a new array by applying a provided function to each element of the original array.array.from()
: Creates a new array from an existing iterable object, such as an array or string.for loop
: Iterates over the elements of the original array using a traditional for loop and assigns each value to a new array.foreach
( likely a typo, it should be "forEach"): Similar to map()
, but uses the forEach()
method instead.slice()
: Creates a shallow copy of a portion of an array, starting from the specified index.spread
( likely referring to Array.prototype spread syntax): Creates a new array by spreading the elements of an existing iterable object.Pros and Cons
slice()
or spread
.map()
.slice()
or other methods.Library Usage
None of the test cases explicitly uses any external libraries.
Special JS Feature/Syntax
The benchmark uses the following features:
e => e
) in map()
.Array.from()
and spread
syntax.for loop
.These features are not specific to JavaScript version or platform, but might be more common in modern development environments.
Alternatives
Other methods for creating a new array include:
concat()
method: const newArr = arr.concat();
push()
method with an array: const newArr = []; newArr.push(...arr);
reduce()
: const newArr = arr.reduce((acc, e) => acc.concat(e), [])
These alternatives might have different performance characteristics and use cases compared to the methods tested in this benchmark.