addEventListener test with immediate function vs declared function

JavaScript performance comparison

Test case created by Satheesh

Info

This is an attempt to understand adding event handlers inline or already defined handlers performs better. See the preparation code.

Apparently I was not able to get an answer. If I reverse the test order the winner also reverses. The first test is always the winner

Preparation code

<button id="myTestButton1"></button>
<button id="myTestButton2"></button>
<script>
Benchmark.prototype.setup = function() {
    function clickHandler() {
      console.log("hi");
    }
   
    document.getElementById("myTestButton1").addEventListener("click", clickHandler);
   
    document.getElementById("myTestButton2").addEventListener("click", function(e) {
      console.log("hi");
    });
   
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
With declared handler
document.getElementById("myTestButton1").click();
pending…
With handler defined inline
document.getElementById("myTestButton2").click();
 
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

Satheesh (revision owner) commented :

What I observed the test results are not accurate. If I reverse the test order "With handler defined inline becomes the winner".

Share your thoughts.

Add a comment