Handler Speed: Bind vs addEventListener

JavaScript performance comparison

Revision 3 of this test case created by Ken Snyder

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<button id="button1" type="button">
  Button1
</button>
<button id="button2" type="button">
  Button2
</button>
<script>
Benchmark.prototype.setup = function() {
    function simulateClick(element) {
      var event = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        detail: Math.random()
      });
      element.dispatchEvent(event);
    }
    function setColor1(){
      button1.style.color = '#ff0000';
    }
    function setColor2(){
      button2.style.color = '#0000ff';
    }
    function $2(element) {
      this.elements = [element];
    }
    $2.prototype.addEventListener = function(event, handler) {
      for (var i = 0, len = this.elements.length; i < len; i++) {
        this.elements[i].addEventListener(event, handler, false);
      }
    }
    var button1 = document.getElementById('button1');
    var button2 = document.getElementById('button2');
    $(button1).on('click', setColor1);
    new $2(button2).addEventListener('click', setColor2);
   
};
</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
Bind
simulateClick(button1);
pending…
Add Event Listener
simulateClick(button2);
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:

0 comments

Add a comment