<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 | 731776.9 Ops/sec |
closest comma | 1074021.6 Ops/sec |
The benchmark is testing the performance of two different approaches for finding the closest ancestor of a specified element in a DOM structure using the Element.closest()
method in JavaScript. Both tests compare how quickly this method can locate elements based on CSS selectors when executed multiple times.
Closest Loop
['.aa', '.bb', '.cc', '.dd', '.ee', '.ff'].forEach(letter => element.closest(letter))
element.closest(letter)
is called for each class in the array.Closest Comma
element.closest('.aa, .bb, .cc, .dd, .ee, .ff')
element.closest()
with a string of comma-separated selectors. This method retrieves the closest ancestor that matches any of the specified selectors in one go.Pros:
Cons:
closest()
, which can be computationally expensive, especially in a loop.Pros:
Cons:
The benchmark results indicate that the Closest Comma approach performed significantly better than the Closest Loop approach:
This shows that using a single call to closest()
with multiple selectors (comma-separated) is more efficient in terms of execution speed when compared to iterating through a list of selectors one by one.
When conducting such benchmarks, it's essential to consider the environment in which the tests are run. Factors like browser version, operating system, and even the device being used may affect performance. In this case, all tests were executed on a specific version of Chrome on a Mac OS.
Aside from the Element.closest()
method, other potential alternatives for finding ancestor elements in a DOM structure include:
parentElement
or parentNode
, loop through parents until a matching element is found.By analyzing these approaches, engineers can choose the most suitable method based on the specific needs of their application, balancing performance and code maintainability.