title: How to optimize jQuery event handlers for speed
body: <p>I'm trying to speed up the javascript execution in our app.</p>
  
  <p>It looks like I've 900+ event listeners bound -</p>
  
  <pre><code>var listenerCount = 0;    
  var ael = Node.prototype.addEventListener;
  Node.prototype.addEventListener = function() {
       listenerCount++;
       ael.apply(this, arguments);
  }
  </code></pre>
  
  <p>And I understand that this will be effecting performance. Is it possible to speed things up by adjusting the way I register listeners? For example if I try and register <code>on</code> events on the same element (with different selectors), will that be more efficient.</p>
  
  <p>Eg changing</p>
  
  <pre><code>$('#sidebar').find('select').on('click', 'option', handler1);
  $('#sidebar').find('.className').on('click', 'a', handler2);
  </code></pre>
  
  <p>for</p>
  
  <pre><code>$('#sidebar').on('click', 'select option', handler1);
  $('#sidebar').on('click', '.className a', handler2);
  </code></pre>
  
  <p>Generally speaking I'm interested in the time it takes to register everything rather than the time it to actually run the handler (and I'm aware that different selectors perform differently). I'd probably swap an extra 10-50ms when the event is actually fired for 1-5ms reduction in registering the event - I want the app to load fast!</p>
  
  <p>I was thinking of writing something that will do the selector matching so as to reduce the number of events actually registered, but I can't find anyone else doing anything similar (which makes me think it's probably dumb) -</p>
  
  <pre><code>var sideBarDomEvents = (function(){
      var clickEvents = [],
      my = {
        init: function() {
          $sidebar = $('#sidebar');
          $sidebar.on('click', function(e){
            for (var i=0; i &lt; clickEvents.length; i++) {
              if (clickEvents[i]['target'] == $(e.target) {
                clickEvents[i]['handler'](e);
              }
            }
          });
        },
        registerClickEvent: function($target, handler){
          // This only works if the target is the inner most element - bubbling isn't supported!
          clickEvents.push({'target':$target, 'handler': handler});
        }
      }
      return my;
  })();
  </code></pre>
  
  <p>I'm really not sure which way to go here - I don't even know where to measure this stuff (I certainly haven't noticed anything in Chrome's profile or timeline that relates). Any explanation of the performance effects of jquery events would be great.</p>