var iterations = 10000;
const array = [];
for (i = 0; i < iterations; i++) {
array[i] = i;
}
Array(iterations).fill('')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
fill |
Test name | Executions per second |
---|---|
for | 75854.4 Ops/sec |
fill | 190831.8 Ops/sec |
The JSON benchmark you provided tests the performance of two different ways of populating an array in JavaScript: using a for
loop and using the Array.fill()
method.
Name: Array fill vs loop
Script Preparation Code: A variable iterations
is defined with a value of 10,000, which means that both methods will attempt to populate an array with 10,000 elements.
For Loop:
const array = [];
for (i = 0; i < iterations; i++) {
array[i] = i;
}
for
loop to fill in the array. Each index i
from 0 to iterations-1
is assigned to the corresponding position in the array.Pros:
Cons:
Array.fill():
Array(iterations).fill('')
iterations
) and fills every element in that array with an empty string (''
).Pros:
Cons:
<Array>.fill()
can be less intuitive than a traditional loop for those unfamiliar with this method.From the results, the Array.fill()
method outperforms the for
loop in executing the same operation. This indicates that Array.fill()
may leverage internal optimizations that make it faster for filling arrays.
When considering performance in array handling, using the built-in array methods like Array.fill()
is generally recommended due to potential optimizations by the JavaScript engine. However, traditional loops might still be more appropriate for complex operations that require conditional logic or data processing.
Other alternatives for populating arrays in JavaScript include:
Array.from({ length: iterations }, (_, i) => i);
map()
function to transform it.Each of these methods comes with its own pros and cons related to readability, flexibility, and potential performance, depending on the specific case you are dealing with.