thelolcat
thelolcat

Reputation: 11545

Any performance gain when binding to event on multiple elements at once?

I was wondering if attaching an event handler to a jQuery collection is faster than looping over the elements and attaching the event handler on each element.

var stuff = $();

// then some code that builds the list
// stuff = stuff.add(...);

stuff.on('change', ...

versus an array that holds the elements:

for (var i = 0; i < stuff.length; i++)
  $(stuff[i]).on('change', ...

I'm asking becaue I'm in the position of having to choose the event (change or input) based on the type of input

Upvotes: 0

Views: 164

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

I would suggest doing stuff.on over $(stuff[i]).on because jQuery essentially does that for you under the hood.

If you look at the source code you'll see that they do the following:

return this.each( function() {
    jQuery.event.add( this, types, fn, data, selector );
});

where add is the actual function used to attach event listeners. If you're absolutely concerned with performance than you can push it faster by bypassing jQuery all together and attach listeners more manually:

function onChangeListener() { ... }
for (var i = 0, len = stuff.length; i < len; i++) {
    stuff[i].addEventListener('change', onChangeListener);
}

But addEventListener isn't 100% supported by older browsers and jQuery will take care of that detail for you.

Another major detail to keep in mind is that every time you do $(something) a new object is created which will definitely make the second method less performant.

If at all possible, you may want to attach to the parent element (assuming everything in stuff is under a common parent) and pick up the events there. That will definitely be the best option if applicable.

TL;DR Just do $(selector).on(event, callback). You'll save yourself some cycles, memory, and heartache.

Upvotes: 1

Related Questions