Which of these two is better/faster?
var a = $('.listItem', $('#myList'));
vs
var a = $('#myList .listItem');
Which of these two is better/faster?
var a = $('.listItem', $('#myList'));
vs
var a = $('#myList .listItem');
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.
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.
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");
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.