Is there a performative difference between on chained with on with multiple events?

Asked

Viewed 51 times

3

I have always used the on with multiple events with the thought that it would simplify my code and make it easier to understand, but from time to time I came across several plugins using the on in a chained way.

Example with multiple events:

$('#foo').on('click , dblclick', function(e) {
  if (e.type === 'click') {
    console.log('click');
  } else {
    console.log('double click');
  }
});

Chained example:

$('bar').on('click', function() {
  console.log('click');
}).on('dblclick', function() {
  console.log('double click');
});

Analytically, there is some advantage/disadvantage of one approach to another ? there is some case that would take a slower?

1 answer

2


There is no difference in performance, underneath the scenes both versions saw a simple elem.addEventListener( type, eventHandler, false ); for each event you have passed (where type is the name of the event), so no matter the shape, the amount of Event listeners will be the same at the end. It also has the factor that there is a break in the string to identify that 'click dblclick' are two events, yet even passing only one event as 'dblclick' this string processing takes place in the same way.

On approach advantage, it depends on the context. In your examples I think the second version is clearer by not including a if-else, but this is subjective.

Note: in fact there is a factor of difference of performance, its version with multiple events has ifs, however the cost of this is negligible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.