Jquery sort speed

Which of these two is better / faster?

var a = $('.listItem', $('#myList')); 

vs

 var a = $('#myList .listItem'); 
+4
source share
4 answers

First of all, you are doing it wrong in a weird way. It should be:

 var a = $('.listItem', '#myList'); 

And according to Resig , the find() method turned out to be the fastest in most cases:

 var a = $("#myList").find(".listItem"); 
+5
source

The only real way to find out is to profile them; this is really the only answer that can be asked to a question. In the first case, there will be a slight performance hit, as the context works best when it is an element, not a jQuery object .

+3
source

The second, of course, is easier to read and simplifies the code.

... which, in my opinion, makes it better.

They should produce the same results.

0
source

To record

 var a = $('.listItem',$('#myList')); 

will execute exactly the same as:

 var a = $('#myList').find('.listItem'); 

In my tests, this works faster :

 var a = $('#myList > .listItem'); 

Oh and:

 var a = $('.listItem', '#myList'); 

wrong . (edit) matches the first example.


EDIT:

I am an idiot. The last example is exactly the same as in the first example in terms of functionality . As for speed, I can’t say. My wild guess was that since in the first example the jQuery object already has the elements requested by the selector, it will be a little faster than the last example, which would still have to find the elements.

0
source

All Articles