<div id='div1'>
<div id='div2'>
<div id='div3'>
</div>
</div>
</div>
const box = document.getElementById('div1')
const clicked = document.getElementById('div3')
const isClickInside = box.contains(clicked);
return isClickInside
const box = document.getElementById('div1')
const clicked = document.getElementById('div3')
const isClickInside = clicked.closest('#div1');
return isClickInside
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
contains | |
closest |
Test name | Executions per second |
---|---|
contains | 2040790.4 Ops/sec |
closest | 1822871.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance difference between two approaches: contains
and closest
. Both methods are used to determine whether an element (clicked
) is contained within another element (box
), which is a child of the DOM node with ID "div1".
Options Compared
Two options are being compared:
contains()
: This method returns true
if the specified element is contained in the given container, and false
otherwise.closest()
: This method returns the closest ancestor of the specified element that matches the given selector.Pros and Cons of Each Approach
contains()
:box
element is very deep in the DOM tree (i.e., many ancestor elements), since the method has to traverse all those ancestors.closest()
:contains()
.Library Used
The benchmark uses the DOM API, specifically the document.getElementById()
method to retrieve elements by their IDs. The closest()
method is also part of this API.
Special JavaScript Feature/Syntax
There's no special JavaScript feature or syntax being used in this benchmark beyond standard DOM manipulation and access methods (e.g., document.getElementById()
, .contains()
).
Other Considerations
When running benchmarks like this, you might want to consider factors such as:
Alternatives
If you were to write a similar benchmark, you might consider testing other approaches:
contains()
and closest()
, use query selectors like box.contains(clicked)
and clicked.closest('#div1')
.Keep in mind that different benchmarks will have different characteristics, so consider what makes sense for your specific use case.