George
George

Reputation: 3953

Javascript Performance Implication of Selecting All Items

I always feel bad when I see code like this

$('input[type=checkbox]').on('click', doSomething);

I normally prefer exposing the functionality through a function and having other developers call that function with a target element, just like below.

var onClick = (function ($) { return function ({ id }) {
   $(id).on('click', doSomething);
} })(jQuery);

onClick({id: '#some-element'})

or instead of id I sometimes use class names. Even though I am yet ton test this, I know strongly that there is going to be a performance issue with the first approach, but I don't have enough reasons to ask someone not to use it especially when the target elements are only few.

I will like to know if the first/second approach is really a bad idea and why.

Upvotes: 0

Views: 40

Answers (2)

llama
llama

Reputation: 2537

I see no reason why the first example would have any worse performance than the second, and in fact, it's probably a tiny better in that regard.

Your second example seems to be missing some information. Maybe you meant to invoke the returned function with a selector, like this.

(function ($) { return function ({ id }) {
   $(id).on('click', doSomething);
} })(jQuery)({id: 'input[type=checkbox]'});

Either way, wrapping it in a function (or functions) that you execute first shouldn't give any performance benefit, and will likely incur a tiny cost at the point of execution.


If you're talking purely about the idea of abstracting behavior behind functions, there should be a reasonable limit. I mean jQuery is already a pretty massive abstraction, so to hide minimal functionality behind another function seems misguided. The .on() method is concise enough, and the handler is already in a named function that can be reused.

Naturally there will be performance implications to selecting all items vs selecting just one, but then if you need all, why would you only select one?

If you're talking about using event delegation, then there may be a tiny benefit when binding, but a cost when the delegate analyzes the code.

If you're talking about selecting all the same elements one at a time, each by its own ID, that'll could have a greater cost than selecting them all, but it all depends on the exact situation.

Upvotes: 1

Prashant
Prashant

Reputation: 151

First approach is totally fine.

Yup, in case you have dynamic append of checkbox during user interaction then you can bind your code with body also

Upvotes: 0

Related Questions