let arrayTest = new Array(10000000);
for (let i = 0; i < arrayTest.length; i++){
arrayTest[i] = 0;
}
let arrayTest = new Array(10000000).fill(0);
Array(10000000).map((_, i) => i);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For Loop fill | |
Array Fill | |
map |
Test name | Executions per second |
---|---|
For Loop fill | 10.1 Ops/sec |
Array Fill | 9.8 Ops/sec |
map | 113.2 Ops/sec |
I'd be happy to help explain the benchmark and its results.
Benchmark Description
The benchmark is designed to compare the performance of three different methods for filling an array with zeros:
fill()
method provided by modern JavaScript arrays to fill all elements with a specified value, in this case, zero.map()
function to create a new array with the same length as the original array, but with each element set to its index.Comparison of Approaches
Here are some pros and cons of each approach:
fill()
method.Library/External Function Used
None of these methods rely on any external libraries or functions beyond what is built into JavaScript itself.
Special JS Feature/Syntax
None of the benchmark's code uses any special JavaScript features or syntax, making it accessible to a wide range of developers.
Other Alternatives
If you need to fill an array with zeros in a different way, here are some alternatives:
Array.from()
and new Array(length).fill(0)
: This method is similar to the for loop approach but uses the from()
function to create an array from an iterable.Array.prototype.set()
: This method allows you to set multiple values in an array at once, which could be faster than filling a large array with zeros.Benchmark Results
The benchmark results show that:
map()
function performed best, with an average execution rate of 113.22110748291016 executions per second.Array Fill
method performed next, with an average execution rate of 10.132774353027344 executions per second.These results suggest that both map()
and Array Fill
are suitable alternatives to the traditional for loop method when filling large arrays with zeros in modern browsers.