Array(10000).fill().map((_, i) => i+1)
Array.from(Array(10000), (_, i) => i+1)
Array.from({length: 10000}, (_, i) => i+1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fill | |
from | |
from object |
Test name | Executions per second |
---|---|
fill | 4407.2 Ops/sec |
from | 1501.3 Ops/sec |
from object | 1045.7 Ops/sec |
I'd be happy to explain what's being tested in this benchmark.
Benchmark Overview
The benchmark measures the performance of three different approaches for creating an array of numbers:
Array.fill()
: Fills an existing array with a specified value.Array.from()
without an object (i.e., only using the spread operator): Creates a new array from an iterable.Array.from()
with an object (i.e., using the Object
constructor to create an object and then passing it to Array.from()
: Creates a new array from an iterable.Options Compared
The benchmark compares the performance of these three approaches:
Array.fill()
: Pros:Array.from()
without an object: Pros:Array.fill()
if the input iterable is very large or complexArray.from()
with an object: Pros:Array.fill()
and the simple Array.from()
Library/Functionality Used
In this benchmark, no external libraries or functions are used. However, it's worth noting that Array.from()
is a built-in JavaScript function that was introduced in ECMAScript 2015.
Special JS Features/Syntax
There are no special JavaScript features or syntax being tested in this benchmark. The focus is on comparing the performance of different array creation approaches using standard JavaScript features.
Alternatives
If you're interested in exploring alternative approaches to creating arrays, here are a few options:
Array.prototype.push()
: Instead of creating an array and then filling it with values, you could use push()
to add elements to an existing array. This approach would require modifying the original array.Uint8Array
or other typed arrays: Depending on your specific use case, using a typed array like Uint8Array
might be more efficient than creating an untyped array using Array
.web Workers
: If you need to create very large arrays and are concerned about performance, you could consider using web workers to offload the array creation task to a separate thread.Keep in mind that these alternatives may not offer significant performance benefits over the approaches being compared in this benchmark.