Which jQuery selection method is faster?

I am wondering if there is any advantage to using a context parameter when choosing jQuery and using a regular CSS selector.

Assuming I have this html:

<div class="contacts">
    <h1>All contacts</h1>
    <div class="contact new">
        <p class="name">Jim Jones</p>
        <p class="phone">(555) 555-1212</p>
    </div>
    <div class="contact new">
        <p class="name">Bob Smith</p>
        <p class="phone">(555) 555-1213</p>
    </div>
    <div class="contact new">
        <p class="name">Dave Baker</p>
        <p class="phone">(555) 555-1214</p>
    </div>
    <div class="contact">
        <p class="name">Pete Harrison</p>
        <p class="phone">(555) 555-1215</p>
    </div>
    <div class="contact">
        <p class="name">George Donald</p>
        <p class="phone">(555) 555-1216</p>
    </div>
    <div class="contact">
        <p class="name">Chris Root</p>
        <p class="phone">(555) 555-1217</p>
    </div>
</div>

If I want to capture all new contacts (marked with a "new" class) from the contacts div, which method is faster, scales better, etc.?

$('.contacts .new');

or

$('.new', '.contacts');

jsFiddle

Update

There are a lot of interesting information in the answers and comments. To summarize the main points, in most browsers, one selector scales better when there are several div.contacts. In most browsers, two selector context methods work faster, only if there is only one .contacts div.

- , , .

$('p:first', '#chapter2'); // get the first paragraph from chapter 2

, .

$('.chapter p:first-child'); // get the first paragraph from all chapters
+5
6

() , , 2 .

+11

$('.contacts .new') , , , . $('.new', '.contacts').contacts, .contacts.

, HTML .contacts, , . .contact, , .

+1

http://jsfiddle.net/cvWA7/1/

, , , $('.contacts .new') 22% .

, . , - .

2 Chrome 13

+1

IIRC, $('.foo', '.bar') $('.bar').find('.foo'), .

$('.foo', '.bar') , $('.foo .bar'), getElementsByClassName sizzle. , , , - .

update: , find() : http://jsperf.com/jquery-selection-method/2

update 2: jQuery - $('.foo', '.bar') $('.bar').find('.foo') - https://github.com/jquery/jquery/blob/master/src/core.js#L171.

+1

, .

context :

DOM, jQuery

: http://api.jquery.com/jQuery/

.

, jQuery :

$('.new', $('.contacts'));

jQuery, . , .

Edit:

: http://jsperf.com/jquery-selection-method/4

, . , .contacts, Opera, . .contacts .

+1
source

Of your two examples, the first selector is likely to be faster. However, if you assign a context to a variable, then use the second method, it is MUCH faster.

contacts = $('div.contacts');
$('.new', contacts);

The results can be seen at http://jsperf.com/jquery-context-with-tagname . If you had a larger HTML document that a class prefix with a tag name would probably also provide better performance.

+1
source

All Articles