Combined or Separate Event Handlers

JavaScript performance comparison

Revision 3 of this test case created by Pat

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="elm"></div>
<script>
Benchmark.prototype.setup = function() {
    var $doc = $(document), $elm = $('#elm');
};

Benchmark.prototype.teardown = function() {
    $doc.off('click keydown keyup focus blur mouseover mouseout');
};
</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
Combined
$doc.on('click keydown keyup focus blur mouseover mouseout', '#elm', function(e){
  switch(e.type) {
    case 'click':
      break;
    case 'keydown':
      break;
    case 'keyup':
      break;
    case 'focus':
      break;
    case 'blur':
      break;
    case 'mouseover':
      break;
    case 'mouseout':
      break;
  }
});

$elm.trigger('click');
$elm.trigger('keydown');
$elm.trigger('keyup');
$elm.trigger('focus');
$elm.trigger('blur');
$elm.trigger('mouseover');
$elm.trigger('mouseout');
pending…
Separate
$doc.on('click', '#elm', function(e){

});

$doc.on('keydown', '#elm', function(e){

});

$doc.on('keyup', '#elm', function(e){

});

$doc.on('focus', '#elm', function(e){

});

$doc.on('blur', '#elm', function(e){

});

$doc.on('mouseover', '#elm', function(e){

});

$doc.on('mouseout', '#elm', function(e){

});

$elm.trigger('click');
$elm.trigger('keydown');
$elm.trigger('keyup');
$elm.trigger('focus');
$elm.trigger('blur');
$elm.trigger('mouseover');
$elm.trigger('mouseout');
pending…
if/else
$doc.on('click keydown keyup focus blur mouseover mouseout', '#elm', function(e){
  var type = e.type;
  if (type === 'click') {

  } else if (type === 'keydown') {

  } else if (type === 'keyup') {

  } else if (type === 'focus') {

  } else if (type === 'blur') {

  } else if (type === 'mouseover') {

  } else if (type === 'mouseout') {

  }
});

$elm.trigger('click');
$elm.trigger('keydown');
$elm.trigger('keyup');
$elm.trigger('focus');
$elm.trigger('blur');
$elm.trigger('mouseover');
$elm.trigger('mouseout');
pending…
object handler
$doc.on({
        'click': function() {},
        'keydown': function() {},
        'keyup': function() {},
        'focus': function() {},
        'blur': function() {},
        'mouseover': function() {},
        'mouseout': function() {}
}, '#elm');

$elm.trigger('click');
$elm.trigger('keydown');
$elm.trigger('keyup');
$elm.trigger('focus');
$elm.trigger('blur');
$elm.trigger('mouseover');
$elm.trigger('mouseout');
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