<div id='test-list'>
<ul>
<li class="item">Item 01</li>
<li class="item">Item 02</li>
<li class="item">Item 03</li>
<li class="item">Item 04</li>
<li class="item">Item 05</li>
<li class="item">Item 06</li>
<li class="item">Item 07</li>
<li class="item">Item 08</li>
<li class="item">Item 09</li>
<li class="item">Item 10</li>
<li class="item">Item 11</li>
<li class="item">Item 12</li>
<li class="item">Item 13</li>
<li class="item">Item 14</li>
<li class="item">Item 15</li>
<li class="item">Item 16</li>
<li class="item">Item 17</li>
<li class="item">Item 18</li>
<li class="item">Item 19</li>
<li class="item">Item 20</li>
</ul>
</div>
const items = document.querySelectorAll('.item');
const items = document.querySelectorAll('.item');
Array.from(items);
const items = document.querySelectorAll('.item');
[items]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from() | |
Spread |
Test name | Executions per second |
---|---|
Array.from() | 173524.9 Ops/sec |
Spread | 184150.9 Ops/sec |
Benchmark Explanation
The provided JSON represents a JavaScript benchmarking test case that compares the performance of two approaches: Array.from()
and the spread operator ([...items]
) when working with DOM elements.
Script Preparation Code
const items = document.querySelectorAll('.item');
This code selects all HTML elements with the class item
from the document and assigns them to an array called items
.
Html Preparation Code
<div id='test-list'>
<ul>
<!-- 20 item elements -->
<li class="item">Item 01</li>
...
</ul>
</div>
This HTML code creates a list of 20 DOM elements with the class item
.
Benchmark Definition
The benchmark consists of two individual test cases:
items
array using Array.from()
and performs no operation.items
array using the spread operator ([...items]
) and also performs no operation.The benchmark aims to measure the performance difference between these two approaches when working with large DOM datasets.
Library:
None (no external libraries are used in this benchmark)
Special JS Feature/Syntax:
Pros and Cons of Each Approach:
Other Alternatives:
for...of
loop: Instead of using Array.from()
or the spread operator, you can use a traditional for...of
loop to iterate over the elements in the array.for (const item of items) {
// do something with each item
}
This approach avoids creating an array object and is often more efficient for large datasets.
slice()
or filter()
: Depending on your specific use case, you can use methods like slice()
or filter()
to create a new array from the original one.const newItems = items.slice(0, 10); // take the first 10 elements
This approach provides more control over the iteration process and can be more efficient than using Array.from()
or the spread operator.