for (i=0; i<100;i++) {
document.addEventListener('click', ()=>{})
}
for (i=0; i<100;i++) {
$('document').on('click', ()=>{})
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
addEvenListener | |
.on |
Test name | Executions per second |
---|---|
addEvenListener | 59.5 Ops/sec |
.on | 630.8 Ops/sec |
Let's break down what's being tested in the provided benchmark.
Benchmark Definition
The benchmark is comparing two approaches to attach an event listener to the document
object:
addEventListener
method:for (i=0; i<100;i++) {
document.addEventListener('click', ()=>{})
}
.on()
method (likely a jQuery alias for addEventListener
):for (i=0; i<100;i++) {
$('document').on('click', ()=>{})
}
Options Compared
The two approaches are being compared in terms of their performance, which is measured by the number of executions per second.
Pros and Cons of Each Approach
addEventListener
:data-addEventListener
) to the document
element..on()
method:addEventListener
.Other Considerations
Both approaches have security implications. In the case of addEventListener
, if you don't properly sanitize the callback function, it could lead to code injection vulnerabilities. The .on()
method, being a jQuery alias for addEventListener
, inherits this same vulnerability.
Library and Its Purpose
The .on()
method is likely using jQuery's internal state management mechanisms, which provide a convenient way to attach event listeners across multiple elements without having to use addEventListener
explicitly.
Special JS Feature or Syntax
Neither of the approaches mentioned utilizes any special JavaScript features or syntax. They are both relatively straightforward and rely on standard JavaScript methods.
Alternatives
Other alternatives for attaching event listeners include:
attachEvent
method (available in older Internet Explorer versions):for (i=0; i<100;i++) {
document.attachEvent('onclick', ()=>{})
}
These alternatives may have different performance characteristics and implications depending on the specific use case.
In summary, the benchmark is comparing two common approaches to attach an event listener to the document
object in JavaScript: addEventListener
and the .on()
method (a jQuery alias). The results will indicate which approach is faster for this particular test case.