A few questions about 25 jquery tips

advertisements

I was just reading this: http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx

And had some questions about some of the advocated tricks:

9 - Give your selectors a context:

What's the difference between using a context and using a more specific selector?

Rather than doing

var selectedItem = $('#listItem' + i, $('.myList'));

What about

var selectedItem = $('.myList>#listItem' + i);

Which one is faster/better, or is there no difference?

12 - Learn about event delegation:

I would imagine that at low handler counts event delegation is slower than normal binding.

How many handlers is the time when you should start using event delegation?

Also, what is the difference (in terms of how fast or how 'good' it is) between using delegation and creating a click target in dom, having the user click that click target, and then have the click target find the elements to manipulate. Is this method faster or is delegation faster?

Edit: In addition, how many levels should you be delegating? Is it better to delegate something 10 levels away, or to simply bind 2 handlers.

13 - Use classes to store state

14 - Even better, use jQuery's internal data() method to store state:

Why use data vs classes? Is data faster? I think I generally find classes to be easier to read, contradicting what it says in the blog entry, because I can see it in the DOM.

Thanks!


9 - Give your selectors a context:

var selectedItem = $('#listItem' + i, $('.myList'));

v/s

var selectedItem = $('#listItem' + i);

According to the article the first one should be faster. But I can't see how this can be...

First of all accessing by ID is one of the fastest ways to get to an element. It's just a lookup from global ID-s hash table. Adding a context to it should add no speed. Looking up the context should take some extra time and therefore the first example should be slower.

I also did some measurements and found that indeed the first one is many times slower.

As for this:

var selectedItem = $('.myList>#listItem' + i);

That should be about the same speed as the first one. And according to my measurements it is indeed about the same, just a little faster.

But the specifying context can be beneficial when dealing with other types of selectors and especially you reuse it, like that:

var ctx = selectedItem = $('.myList')
for (var i=0; i<1000; i++) {
    var selectedItem = $('.listItem' + i, ctx);
}

In this example it gives you a considerable speed boost.

Like with everything else related to performance - you have to measure before you know if something applies in your specific situation.

How many handlers is the time when you should start using event delegation?

When I feel that the page is slow. 99% of the time normal event handlers are good enough.