var str = "string";
var n = 1000;
var res = Array(n).fill(str)
var res = Array.from({ length: n }, _ => str)
var res = [];
for (var i = 0; i < n; ++i) {
res.push(str)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array(n).fill(str) | |
Array.from({ length: n }, _ => str) | |
loop |
Test name | Executions per second |
---|---|
Array(n).fill(str) | 238776.2 Ops/sec |
Array.from({ length: n }, _ => str) | 66171.8 Ops/sec |
loop | 97861.0 Ops/sec |
The benchmark defined in the provided JSON tests various methods for creating and populating an array in JavaScript with a specified string value repeated a certain number of times (n = 1000
). The options being compared are:
Array(n).fill(str)
n
and fills it with the specified value str
.str
is an object (as opposed to a primitive value), all elements will reference the same object, which could lead to unintended side effects.Array.from({ length: n }, _ => str)
Array.from()
factory method to create an array from an iterable or array-like object, with the second argument being a mapping function that specifies how to populate each element.Array.fill()
, which may not be as performant with large n
compared to the first method due to the additional function overhead.Manual loop (for loop)
str
into the array in a loop.From the benchmark results, the performance of each method is expressed in terms of executions per second:
str
).When considering alternatives, it’s also worth noting:
Using Spread Operator: const res = [...Array(n)].map(() => str);
Using Higher Order Functions: Methods like Array.prototype.map()
can also be useful for similar tasks but may add complexity and overhead.
Performance Context: While this benchmark provides insights into method performance for a specific case, real-world performance can vary depending on the actual use case (size of n
, frequency of this operation, etc.), execution environment, and specific JavaScript engine optimizations.
Overall, while there are various options to populate an array, the selection should weigh conciseness, readability, and performance relative to the specific requirements of the programming task at hand.