const arr = new Array(100000).fill().map((_,i) => (i))
const arr = [];
for (let i = 0; i < 100000; i++) {
arr.push(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fill | |
for |
Test name | Executions per second |
---|---|
fill | 510.9 Ops/sec |
for | 830.6 Ops/sec |
I'd be happy to explain the benchmark and its various aspects.
What is being tested?
The benchmark compares two approaches to populate an array with 100,000 elements: using the Array.prototype.fill()
method followed by map()
, and using a traditional for
loop.
Options compared
There are two options being compared:
Array.prototype.fill()
method followed by map()
to populate the array.for
loop to iterate over an index range and push elements onto the array.Pros and Cons of each approach
Fill:
Pros:
Array.prototype.fill()
in modern browsersCons:
fill()
For:
Pros:
Cons:
Other considerations
Both approaches have their trade-offs, but the fill()
method is generally preferred due to its conciseness and optimized implementation. However, if you need to support older browsers or require more control over the iteration process, the traditional for
loop may be a better choice.
Library usage
The benchmark uses the Array.prototype.fill()
method, which is a part of the JavaScript standard library. The fill()
method is used to set all elements of an array to a specified value, in this case, creating an array filled with undefined values. The subsequent call to map()
is used to transform each element of the array into its index.
Special JS feature or syntax
The benchmark uses JavaScript's array methods and loops. No special features or syntax are required for this benchmark, making it accessible to a wide range of developers.
Alternatives
Other alternatives for populating an array include:
Array.from()
method, which creates a new array from an iterable.[...new Array(100000)]
) to create an array filled with undefined values.fill
function.However, these alternatives may not be suitable for all use cases or environments, and the traditional for
loop remains a reliable option.