const miArray = Array(100).fill().map((el, i)=> i)
const miArray = Array.from(Array(100), (el, i) => i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fill | |
from |
Test name | Executions per second |
---|---|
fill | 1414385.0 Ops/sec |
from | 292661.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark definition json and individual test cases are designed to compare two different approaches for creating an array in JavaScript: Array.prototype.fill()
and Array.from()
. We'll break down each approach, their pros and cons, and discuss any libraries or special features used.
Approach 1: Using Array.prototype.fill()
The first benchmark definition uses the fill()
method to create an array:
const miArray = Array(100).fill().map((el, i) => i);
Here's what happens:
Array(100)
creates a new array with 100 elements..fill()
sets all elements of the array to a default value (in this case, undefined)..map()
applies a transformation function to each element in the array, returning a new array with the transformed values.Pros:
Cons:
Approach 2: Using Array.from()
The second benchmark definition uses the from()
method to create an array:
const miArray = Array.from(Array(100), (el, i) => i);
Here's what happens:
Array(100)
creates a new array with 100 elements.Array.from()
creates a new array by mapping over the existing array using the provided function.(el, i) => i
is the transformation function that returns each element's index.Pros:
fill()
since it avoids creating an intermediate array.Cons:
from()
.Library and Special Features
Both benchmark definitions use the following libraries or special features:
Array.prototype.fill()
method is used in one approach, while Array.from()
is used in the other.Other Alternatives
Additional approaches for creating arrays in JavaScript include:
[...new Array(100)].map((el, i) => i);
...
): [...new Array(100).keys()];for
loop or forEach()
method to create an array.Each of these approaches has its own pros and cons, and may be more suitable for specific use cases. However, since this benchmark is specifically designed to compare two methods, it's likely that the chosen approaches are optimized for performance and simplicity.
Conclusion
In summary, MeasureThat.net's array_creation_comparison
benchmark tests the performance of two different approaches for creating arrays in JavaScript: Array.prototype.fill()
and Array.from()
. The pros and cons of each approach were discussed, along with any libraries or special features used. Understanding these approaches can help developers choose the most suitable method for their specific use cases.