Eeyore
Eeyore

Reputation: 2126

jquery selectors speed

Which of these two is better/faster?

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

vs

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

Upvotes: 4

Views: 1046

Answers (4)

KyleFarris
KyleFarris

Reputation: 17538

For the record,

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

will perform exactly the same as:

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

In my tests, this works the fastest:

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

Oh, and:

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

is completely wrong. (edit) is the same as the first example.


EDIT:

I'm a moron. The last example is exactly the same as the first example in terms of functionality. As for speed, I can't say. My wild guess would be that since, in the first example, the jQuery object already has the elements asked for by the selector, it would be slightly faster than the last example that would still have to find the elements.

Upvotes: 0

peirix
peirix

Reputation: 37741

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

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

And according to Resig, the find() method has proven to be quickest in most cases:

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

Upvotes: 5

Russ Cam
Russ Cam

Reputation: 125488

The only real way to know is to profile them, that is really the only answer that can be given to the question. There will be a slight performance hit with the first since context works best when it is an element and not a jQuery object.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245399

The second is definitely easier to read and would make the code easier to maintain.

...that in my opinion makes it better.

They should both produce similar performance results.

Upvotes: 0

Related Questions