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

3

I've always used 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 thread in a chained form.

Example with multiple events:

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

Thread chained:

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

Analytically, is there any advantage / disadvantage from one approach to another? is there any case that would slow down?

    
asked by anonymous 01.03.2016 / 19:25

1 answer

2

There is no difference in performance, under the wipes both versions saw a simple elem.addEventListener( type, eventHandler, false ); for each event you passed (where type is the name of the event), so no matter the form, the amount of event listeners will be the same in the end. It also has the factor that there is a string break to identify that 'click dblclick' are two events, however even passing only an event as 'dblclick' this processing of the string occurs in the same way.

About advantage of approach, it depends on context. In your examples I think the second version is clearer by not including if-else , but that's subjective.

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

    
01.03.2016 / 20:04