<div class="a">
<div class="b">
<div class="c">
<div class="d">
<div class="d">
<div class="e">
<div class="f">
<div class="g">
<div class="h">
<div class="i">
<div class="j">
<div class="k">
<div class="l">
<div class="m">
<div class="n">
<div class="o">
<div class="p">
<div class="q">
<div class="r">
<div class="s">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
element = document.querySelector('.s')
}
['aa', 'bb', 'cc', 'dd', 'ee', 'ff'].forEach(letter => element.closest(`.${letter}`))
element.closest(`.aa, .bb, .cc, .dd, .ee, .ff`)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
closest loop | |
closest comma |
Test name | Executions per second |
---|---|
closest loop | 637472.1 Ops/sec |
closest comma | 1081359.2 Ops/sec |
The benchmark provided tests the performance of different approaches for finding the closest ancestor element in the DOM that matches a given selector. It uses the Element.closest()
method in JavaScript.
Closest Loop
forEach
loop to iterate over an array of class names (['aa', 'bb', 'cc', 'dd', 'ee', 'ff']) and calls the closest()
method on the target element for each class.Closest Comma
closest()
method once with a comma-separated string of selectors ('.aa, .bb, .cc, .dd, .ee, .ff'). The closest()
function checks all classes in one go.Pros:
Cons:
closest()
and the overhead of iterating through an array.Pros:
Cons:
Using jQuery: While jQuery provides a closest()
method that abstracts away browser inconsistencies and simplifies DOM manipulation, it typically adds more overhead compared to native methods, particularly if you're only working with straightforward use cases where performance is vital.
Manual DOM Traversal: Developers can implement manual logic to traverse the DOM tree to find the closest parent that meets a condition, but this approach is rarely as efficient or clean as using closest()
.
Performance Libraries: Libraries dedicated to performance measures and DOM handling (like lodash) can provide optimized methods, but they may not reach the performance levels of native methods due to added abstractions.
In summary, for efficiency and leveraging browser optimizations, using the Element.closest()
method with a comma-separated string of selectors appears to be the superior choice in this benchmark scenario.