const length = 50;
Array(length).fill();
Array.from({ length: length });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array(length).fill() | |
Array.from({ length: length }) |
Test name | Executions per second |
---|---|
Array(length).fill() | 7942633.5 Ops/sec |
Array.from({ length: length }) | 6051346.5 Ops/sec |
I'd be happy to explain the benchmark and its results.
Benchmark Overview
The provided benchmark compares two ways to create an array of a specified length in JavaScript:
Array(length)
constructorArray.from()
method with an object having a length
propertyOptions Compared
The two options being compared are:
Array(length)
: This is a native JavaScript constructor that creates an array from a specified length.Array.from({ length: length })
: This method uses the from()
function to create an array from an iterable (in this case, an object with a length
property).Pros and Cons
Array(length)
: Pros:Array.from({ length: length })
: Pros:Array(length)
(works with objects having any property, not just length
)Array(length)
from()
functionLibrary and Purpose
Array.from()
was introduced in ECMAScript 2015 (ES6) as a way to create arrays from iterables.Special JS Feature or Syntax
Other Considerations
When choosing between these two options, consider the specific requirements of your use case:
Array(length)
is likely the better choice.Array.from({ length: length })
might be a better fit.Alternatives
Other alternatives to create arrays include:
[...new Array(length)]
)[]; for (var i = 0; i < length; i++) { arr.push(i); }
)These approaches may have different performance characteristics and use cases compared to the options being tested in this benchmark.