<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
<li>22</li>
<li>23</li>
<li>24</li>
<li>25</li>
<li>26</li>
<li>27</li>
<li>28</li>
<li>29</li>
<li>30</li>
<li>31</li>
<li>32</li>
</ul>
function shuffleArray(array) {
const copy = array.slice(0);
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
const list = Array.from(document.querySelectorAll("ul > li"));
const shuffled = shuffleArray(list);
const sorted = shuffled.toSorted((a, b) => {
return parseInt(a.textContent) - parseInt(b.textContent);
});
const sorted = shuffled.toSorted((a, b) => {
return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_PRECEDING ? 1 : -1;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Sort by textContent | |
Sort by compareDocumentPosition |
Test name | Executions per second |
---|---|
Sort by textContent | 54728.5 Ops/sec |
Sort by compareDocumentPosition | 80779.4 Ops/sec |
The benchmark provided tests the performance of two different methods for sorting a list of DOM elements (in this case, <li>
elements within a <ul>
). The sorting is based on different criteria which are specified in the individual test cases.
Sorting by textContent
:
const sorted = shuffled.toSorted((a, b) => {
return parseInt(a.textContent) - parseInt(b.textContent);
});
textContent
of the <li>
elements (which are strings representing numbers) to integers and sorts them based on the numerical value.Sorting by compareDocumentPosition
:
const sorted = shuffled.toSorted((a, b) => {
return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_PRECEDING ? 1 : -1;
});
compareDocumentPosition
method provided by the DOM API to determine the order of the elements. It checks if one node precedes another in the DOM tree and sorts accordingly.textContent
Pros:
Cons:
compareDocumentPosition
Pros:
Cons:
The benchmark results indicate that sorting by compareDocumentPosition
outperformed sorting by textContent
, achieving approximately 97,645 executions per second compared to 56,034 for sorting by textContent
. This suggests that in this particular scenario, utilizing the DOM's inherent structure for sorting can lead to better performance and may be preferable in high-volume or performance-sensitive applications.
Other methods for sorting DOM elements could include:
sort()
on an array: This could entail extracting the values to an array and sorting them directly, but it would not necessarily improve performance if no direct relationship to the DOM is exploited.Ultimately, the choice of sorting method will depend on specific use cases, performance needs, and developer familiarity with DOM APIs.