<context-provider id="provider">
<div>
<div></div>
<div></div>
<div></div>
<div></div>
<div>
<div>
<span>
<span>
<span>abc</span>
</span>
def
<span>
<span id="foo"></span>
</span>
</span>
</div>
ghi
</div>
</div>
</context-provider>
var context = document.getElementById('provider');
var element = document.getElementById('foo');
var SimpleContextEvent = class SimpleContextEvent extends Event {
data = null;
callback = null;
constructor(callback) {
super('context-request', {bubbles: true, composed: true});
this.callback = callback;
}
};
context.addEventListener('context-request', event => {
if (event.callback) {
event.callback(context);
} else {
event.data = context;
}
event.stopPropagation();
});
var i = 5000;
while (i--) {
let ctx = element;
while (ctx && ctx.nodeName !== 'CONTEXT-PROVIDER') {
ctx = ctx.assignedSlot || ctx.parentNode || ctx.host;
}
if (ctx !== context) {
throw new Error('mismatch');
}
}
var i = 5000;
while (i--) {
let ctxEvent = new SimpleContextEvent();
element.dispatchEvent(ctxEvent);
let ctx = ctxEvent.data;
if (ctx !== context) {
throw new Error('mismatch');
}
}
var i = 5000;
var ctx;
var ctxEvent = new SimpleContextEvent(reply => {ctx = reply;});
while (i--) {
ctx = null;
element.dispatchEvent(ctxEvent);
if (ctx !== context) {
throw new Error('mismatch');
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
while loop + tagName check | |
event propagation | |
event propagation with callback |
Test name | Executions per second |
---|---|
while loop + tagName check | 646.5 Ops/sec |
event propagation | 205.5 Ops/sec |
event propagation with callback | 338.9 Ops/sec |
Overview
The provided JSON represents a benchmark test case for measuring the performance of different approaches to getting a context in a web page. The test compares three methods: a while loop with a tagName check, event propagation with new events, and event propagation with callbacks.
Options Compared
element.dispatchEvent()
. The event's data property is set to the expected context.Pros and Cons
Library Used
The test uses a custom SimpleContextEvent
class, which extends the built-in Event
class. This library is used to create events with custom properties (e.g., data
and callback
). The context-provider
HTML element is also assumed to be a part of this library.
Special JS Feature or Syntax
The test uses some special JavaScript features:
reply => {ctx = reply;}
)."<span>\r\n def\r\n <span>\r\n <span>abc</span>\r\n </span>\r\n></span>"
) to create a complex HTML structure.Other Alternatives
If the test authors want to explore alternative approaches, they could consider:
dispatchEvent()
instead of addEventListener()
).Benchmark Result
The benchmark results show that the "while loop + tagName check" approach is the fastest, followed by "event propagation with callbacks". The "event propagation" approach is the slowest. These results suggest that using event dispatching mechanisms can be an efficient way to get a context in a web page.