let n = 10000, length = 50
const result = []
for (let i = 0; i < n; ++i) {
result.push(Array.from({length:length}).map((_, i) => i + 1))
}
let n = 10000, length = 50
const result = []
for (let i = 0; i < n; ++i) {
result.push(Array(5).fill(0).map(i => i + 1))
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
from | |
fill |
Test name | Executions per second |
---|---|
from | 74.6 Ops/sec |
fill | 582.6 Ops/sec |
Measuring the performance of two different approaches in JavaScript, Array.from
and Array.fill
, is crucial for developers to understand the optimal way to create arrays with a specific length filled with values.
What are we testing?
We're comparing the performance of two approaches:
Array.from()
: This method creates a new array by copying elements from another iterable (such as an array or string) and returns the resulting array.Array.fill()
: This method creates a new array with the specified length, fills it with the provided value, and returns the resulting array.Options compared:
Array.from()
vs Array.fill()
Pros and Cons:
Array.from()
Array.fill()
since it can create an array from any iterable, not just a fixed length.Array.fill()
for large arrays because of the overhead of creating a new array and copying elements from the original iterable.Array.fill()
Array.from()
since it only creates an array with the specified length and fills it directly, without any additional overhead.Array.from()
since you're limited to filling an array with a single value.Library/Functionality:
Other Alternatives:
If you don't want to use Array.from()
or Array.fill()
, there are other ways to create arrays with a specified length:
...
): This method creates an array by spreading elements from another iterable.
let result = [...Array(length)].map((_, i) => i + 1);
* Using `new Array(length)`: This method creates an array with the specified length and returns it.
In summary, when choosing between `Array.from()` and `Array.fill()`, consider the following:
* Use `Array.from()` when you need to create an array from a different data source or require more flexibility in your code.
* Use `Array.fill()` when performance is critical and you only need to fill an array with a single value.
Keep in mind that these are just general guidelines, and the best approach depends on your specific use case and requirements.