var array = Array.from(new Array(1000000), (e, i) => Math.random());
var array2 = array.map((e, i) => e);
var array2 = Array.from(new Array(1000000), (e, i) => array[i]);
var array2 = array.slice();
var array2 = [array];
var array2 = new Array(1000000).fill(0), n=array2.length;
for (let i = 0; i < n; i++) array2[i] = i;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map | |
from | |
splice | |
spread | |
loop |
Test name | Executions per second |
---|---|
Map | 120.1 Ops/sec |
from | 69.9 Ops/sec |
splice | 641.5 Ops/sec |
spread | 111.9 Ops/sec |
loop | 135.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares four methods to create an array of 1,000,000 elements:
map()
Array.from()
with a callback functionslice()
(not actually slicing the original array, but rather creating a new one)...
)Library and Functionality
map()
: This is a built-in JavaScript method that applies a given function to each element of an array. It returns a new array with the results.Array.from()
: This is a built-in JavaScript method that creates a new array from an iterable or an array-like object. The callback function is used to transform each element in the original source.slice()
(not actually slicing): In this benchmark, slice()
is not actually modifying the original array but rather creating a new one using new Array(n).fill(0)
, where n
is the length of the desired array. This method returns a shallow copy of a portion of an array.Special JS Feature or Syntax
...
): This is a relatively modern JavaScript syntax introduced in ES6 (ECMAScript 2015). It allows you to create a new array by "spreading" elements from an existing array.Test Cases and Results
The test cases are executed multiple times, and the results show the number of executions per second for each method. The results indicate that:
loop()
is the fastest method, followed closely by map()
.Array.from()
with a callback function is slower than loop()
and map()
, but faster than slice()
(which is not actually slicing).spread
is the slowest method.Pros and Cons of Each Approach
length
).loop()
since it allows for transforming each element using a callback function.new Array(n).fill(0)
....
):Alternatives
If you're looking for alternatives to these methods, consider the following:
loop()
, use Array.from()
with no callback function or a simple transformer function. This can be faster and more concise.map()
, if performance is critical, consider using an optimized transformation function or reducing the number of iterations.Buffer.alloc()
or Uint8Array.alloc()
to create a buffer-based array.Keep in mind that these alternatives may have different trade-offs and requirements depending on your specific use case.