<!--your preparation HTML code goes here-->
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
new Array(500).fill(0)
[Array(6)].map(x => 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array(500).fill(0, 0, 500) | |
[...Array(6)].map(x => 0); |
Test name | Executions per second |
---|---|
new Array(500).fill(0, 0, 500) | 2900678.5 Ops/sec |
[...Array(6)].map(x => 0); | 35458124.0 Ops/sec |
The provided benchmark definition tests various methods for creating and populating arrays in JavaScript. Specifically, it compares two different approaches to achieving similar outcomes using array creation and filling methods:
Using new Array(500).fill(0)
:
new Array(500).fill(0, 0, 500)
.fill
method assigns the value 0
to all elements in the array.new Array(length)
without initializing values could lead to unnecessary memory usage and performance overhead, especially when filling is not performed.fill
can lead to misunderstandings about memory allocation, as the fill operation does not affect the prototype chain.Using the spread operator and map
:
([...Array(6)].map(x => 0));
[...]
, and then it utilizes the map
method to apply the function x => 0
, which fills all slots with the value 0
.From the benchmark results, we see varying executions per second for each method:
([...Array(6)].map(x => 0);)
yields 35,458,124.0 executions per second.new Array(500).fill(0, 0, 500)
shows 2,900,678.5 executions per second.Performance-wise: The first approach (new Array(500).fill(0)
) appears to perform significantly slower than the second method involving the spread operator and map
. This could be due to execution overhead when filling succinctly with fill()
compared to mapping.
Alternative Approaches:
Array.from({length: 500}, () => 0)
creates an array of a specified length and initializes all values using a mapping function. This would be a more readable and functional alternative compared to traditional methods.let arr = new Array(500);
for (let i = 0; i < arr.length; i++) {
arr[i] = 0;
}
Array.prototype.forEach()
can implement initialization processes in more complex scenarios.In summary, this benchmark demonstrates two effective yet different strategies for creating and populating arrays in JavaScript, highlighting their respective performance characteristics, advantages, and potential limitations. Software engineers can select the most suitable method depending on context, readability, and performance needs when working with arrays.