<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='4'></div>
<div id='5'></div>
<div id='6'></div>
<div id='7'></div>
<div id='8'></div>
<div id='9'></div>
<div id='10'></div>
var divs = document.querySelectorAll('div');
Array.from(divs).map(div => div.id);
Array.from(divs, (div) => div.id)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.from.map | |
array.from with map |
Test name | Executions per second |
---|---|
array.from.map | 324814.5 Ops/sec |
array.from with map | 293268.1 Ops/sec |
The provided JSON represents a JavaScript microbenchmark test case on the MeasureThat.net website. The goal of this benchmark is to compare the performance of two approaches: using Array.from
with an arrow function (div => div.id
) and using Array.from
followed by calling the map()
method on the resulting array.
Options being compared:
Array.from(divs, (div) => div.id)
: This approach creates a new array from the divs
element collection and then uses an arrow function to transform each element into its id
property.Array.from(divs).map(div => div.id)
: This approach creates a new array from the divs
element collection using Array.from
, and then applies the map()
method to the resulting array, which also transforms each element into its id
property.Pros and Cons:
Array.from(divs, (div) => div.id)
:Array.from(divs).map(div => div.id)
:map()
) that immediately conveys the intent of transforming each element. Additionally, this approach avoids creating an extra function object.map()
might make the code less readable for some developers who are not familiar with this pattern.Library used:
The provided benchmark code uses the HTML5 Array.prototype.from
method (implemented in WebKit) and the map()
method, which is a part of the ECMAScript standard. The Document.querySelectorAll('div')
method is used to retrieve an array-like object containing all <div>
elements on the page.
Special JS feature or syntax:
None mentioned in this benchmark. However, it's worth noting that Array.prototype.from()
and map()
are part of ECMAScript standard, which means they are supported by most modern JavaScript engines.
Other alternatives:
Other approaches to achieve similar results could include using:
for
loop or forEach
method)reduce()
, filter()
, or every()
Keep in mind that the performance differences between these approaches are likely to be very small, and other factors like the specific use case, data size, and JavaScript engine being used may have more significant impacts on performance.