var audio = document.createElement("audio");
function andAOne(e){
e.count = (e.count|| 0) +1;
}
function stop501(e){
e.count === 501 && e.stopPropagationImmediately();
}
for (var i = 0; i <1000; i++)
audio.addEventListener("ratechange",andAOne.bind({}));
audio.playbackRate = 2;
for (var i = 0; i <1000; i++)
audio.addEventListener("ratechange",andAOne.bind({}));
audio.addEventListener("ratechange",stop501);
audio.playbackRate = 2;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
running async 1000 event listeners | |
running async 501 event listeners |
Test name | Executions per second |
---|---|
running async 1000 event listeners | 2.4 Ops/sec |
running async 501 event listeners | 0.8 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark measures the cost of calling an event listener in JavaScript. The script preparation code creates an audio
element, defines two functions: andAOne
and stop501
, and sets up a playback rate for the audio. The HTML preparation code is empty, which suggests that the benchmark only runs in the browser's context and doesn't rely on any specific HTML structure.
Test Cases
There are two test cases:
audio
element 1000 times, using the andAOne
function as the listener, and sets the playback rate to 2. The goal is to measure the cost of creating and executing this many event listeners asynchronously.audio
element 501 times, using a combination of both andAOne
and stop501
functions as listeners, and also sets the playback rate to 2. The goal is to measure the cost of creating and executing these many event listeners asynchronously.Options Compared
The benchmark compares two approaches:
andAOne
) for all 1000 or 501 additions.andAOne
and stop501
as event listeners for all 1000 or 501 additions.Pros and Cons
Libraries and Special JS Features
There is no explicit mention of any libraries or special JavaScript features being used in these benchmark definitions. The script preparation code only uses standard JavaScript constructs such as document.createElement
, functions, and event listeners.
Other Considerations
To get a more accurate representation of the cost of event listeners, it's essential to consider factors like:
In addition to these considerations, running multiple iterations of each test case can help increase the accuracy of the benchmark results.
Alternatives
Some alternative approaches to measuring the cost of event listeners include:
These alternatives can provide more accurate and detailed insights into the cost of event listeners, but they may require additional setup and expertise.