LENGTH = 10000;
count = 0;
Array.from({length: LENGTH}, () => count++)
Array(LENGTH).fill().map(() => count++)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Array, fill, map |
Test name | Executions per second |
---|---|
Array.from | 857.7 Ops/sec |
Array, fill, map | 1148.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is being tested?
The benchmark measures the performance difference between two approaches to create and populate an array: Array.from()
and a manual implementation using Array
, fill()
, and map()
methods.
Options compared:
Two options are compared:
Array.from({length: LENGTH}, () => count++)
: This approach uses the Array.from()
method to create an array with LENGTH
elements, where each element is generated by a callback function that increments a counter variable count
.Array(LENGTH).fill().map(() => count++)
: This approach creates an array of length LENGTH
, fills it with a single value using fill()
, and then maps over the array to generate the same elements as in the first approach.Pros and cons:
Array.from()
method:Array.from()
and other methods can be small, especially for smaller arrays.Array
, fill()
, and map()
methods:Array.from()
might be noticeable for large arrays.Library used:
There is no specific library used in these benchmarks. However, it's essential to note that both approaches are built into the JavaScript standard library, which means they are optimized for performance by the browser engines (e.g., V8 in Chrome, SpiderMonkey in Firefox).
Special JS feature or syntax:
The only special aspect of this benchmark is the use of the let
keyword with a block scope variable (count
). This was introduced in ECMAScript 2015 (ES6) and allows for the declaration of variables without the var
keyword, which can lead to better code readability and fewer issues due to scoping.