[new Array(500)].fill('').map((_, i) => i);
Array.from({ length: 500 }).map((_, i) => i);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
[...new Array(N)] | |
Array.from({ length: N }) |
Test name | Executions per second |
---|---|
[...new Array(N)] | 462999.5 Ops/sec |
Array.from({ length: N }) | 56994.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros/cons of different approaches.
Benchmark Overview
The benchmark compares two methods for creating an array in JavaScript:
[...new Array()]
)Array.from()
with a length propertyThese two methods are used to create an array of length N
, filled with empty strings, and then map over it to produce an array of integers.
What's being tested
The benchmark measures the execution time for each method on various devices (desktop) using different browsers (Chrome 103). The test results show the number of executions per second for each test case.
Comparing options
There are two main methods being compared:
Array
object. It's a simple and concise way to create an array.Array.from()
function to create an array from an object with a specified length.Pros/Cons of each approach
[...new Array(N)]
, as it can create an array from any type of objectArray.from()
Library usage
None of the test cases use any external libraries. The only library used is JavaScript itself, which provides the built-in methods Array.from()
.
Special JS feature or syntax
The test cases do not use any special JavaScript features or syntax beyond the standard array methods mentioned above.