<div class='div1'>
<div class='div2'>
<div class='div3'>
</div>
</div>
</div>
var box = document.querySelector('.div1')
var clicked = document.querySelector('.div3')
return box.contains(clicked);
return clicked.closest('.div1');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
contains | |
closest |
Test name | Executions per second |
---|---|
contains | 3688147.0 Ops/sec |
closest | 3722269.8 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
What is being tested?
The test case measures the performance difference between two methods:
classList.contains()
: This method checks if an element with a given class name exists in the element's class list.closest()
(which seems to be a custom or library-based implementation of closest()
): This method finds the closest ancestor element matching a certain selector.Options compared
The two methods are being compared, and their performance is measured under different scenarios.
Pros and Cons of each approach:
classList.contains()
:closest()
(library-based implementation):classList.contains()
, as it can handle complex ancestor relationships.Library used:
The closest()
method is likely using the querySelector
API with a custom selector (e.g., .div1 ~ .div2 .div3
). However, without more information, it's difficult to pinpoint the exact library being used.
Special JS feature/syntax:
There doesn't appear to be any special JavaScript features or syntax being utilized in this benchmark.
Other alternatives:
In addition to classList.contains()
and closest()
, other methods for finding closest ancestors or checking class existence might include:
querySelector
with a more complex selector (e.g., .div1 ~ .div2 .div3
).closest()
methodBenchmark preparation code and HTML
The provided Script Preparation Code
and Html Preparation Code
are used to create the test environment:
var box = document.querySelector('.div1')
var clicked = document.querySelector('.div3')
<div class='div1'>
<div class='div2'>
<div class='div3'>
</div>
</div>
</div>
These create a simple HTML structure with three div elements, where box
is the first-level container and clicked
is the second-level child.