<!--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();
}
var arr = ['', '', ''];
const ARRAY_LENGTH = 10000;
new Array(ARRAY_LENGTH).fill(0)
Array.from({ length: ARRAY_LENGTH })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array + fill | |
Array.from |
Test name | Executions per second |
---|---|
new Array + fill | 173013.9 Ops/sec |
Array.from | 5660.7 Ops/sec |
The provided benchmark compares two JavaScript methods for creating an array of a specified length: using new Array(length).fill(0)
and using Array.from({ length })
. Both approaches are commonly employed in JavaScript for initializing arrays, but they have distinct performance characteristics and variations in usage.
new Array(length).fill(0):
0
).fill
method operates on an existing array instance, which can lead to performance overhead when the array is large.Array.from({ length: ARRAY_LENGTH }):
length
property is passed in, leading to the creation of an array whose size is defined by that length.From the benchmark results, we can observe the performance of each method:
This indicates that new Array(length).fill(0)
significantly outperforms Array.from({ length })
in this specific setup. The results suggest that while Array.from
can offer flexibility, it may introduce more overhead compared to directly creating and filling an array with new Array
.
When deciding which method to use, consider the following:
new Array(length).fill(0)
.Array.from({ length })
is more suited.Other alternatives for creating arrays in JavaScript include:
([...Array(ARRAY_LENGTH)].map(() => 0))
to create a filled array, although this is less efficient than the two methods tested.Array.apply(null, Array(ARRAY_LENGTH)).map(() => 0)
, though performance characteristics may vary.Uint8Array
) as they provide better performance and memory efficiency for large arrays.In summary, the choice between new Array(length).fill(0)
and Array.from({ length })
will depend on the specific requirements of your project, such as performance needs, initialization values, and the overall context of array usage.