<context-provider id="provider">
<div>
<div></div>
<div>
<span>
<span>
<span>abc</span>
</span>
def
<span>
<span id="foo"></span>
</span>
</span>
ghi
</div>
</div>
</context-provider>
var context = document.getElementById('provider');
var element = document.getElementById('foo');
var SimpleContextEvent = class SimpleContextEvent extends Event {
data = null;
constructor() {
super('context-request', {bubbles: true, composed: true});
}
};
context.addEventListener('context-request', event => {
event.data = 'abc';
event.stopPropagation();
});
var i = 5000;
while (i--) {
let ctx = element;
ctx = ctx.closest('context-provider');
}
var i = 5000;
while (i--) {
let ctx = element;
while (ctx) {
if (ctx.tagName === 'CONTEXT-PROVIDER') {
break;
}
ctx = ctx.parentNode;
}
}
var i = 5000;
while (i--) {
let ctxEvent = new SimpleContextEvent();
element.dispatchEvent(ctxEvent);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
closest with element selector | |
while loop + tagName check | |
event propagation |
Test name | Executions per second |
---|---|
closest with element selector | 703.0 Ops/sec |
while loop + tagName check | 475.8 Ops/sec |
event propagation | 56.3 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of three approaches to get a context element in a web page: using closest()
with an element selector, using a while loop with a tagName check, and simulating event propagation.
Options Compared
closest()
method on an element reference to find the closest ancestor that matches a CSS selector.<context-provider>
element).event.stopPropagation()
.Pros and Cons
closest()
.Libraries Used
closest()
method, which is a part of the DOM API in modern browsers. However, since this benchmark aims to measure performance across different browsers and platforms, we can assume that some older browsers might not support this method or may behave differently.Event
class and its methods (dispatchEvent()
, stopPropagation()
).Special JS Features/Syntax
SimpleContextEvent
).Alternatives
closest()
, you could use other DOM query methods like getElementById()
or getQuerySelector()
to find the closest ancestor element.jsdom
or cheerio
to simplify DOM manipulation and query execution.Keep in mind that the choice of implementation will depend on the specific requirements of your project and the trade-offs between performance, readability, and maintainability.