Which of these selectors is most likely to be faster?

A few questions actually,

Considering the following two return the same result set

$("#MyTable tr");
$("tr", "#MyTable");

      

is there a performance difference between using the parent child selection selector convention or instead of context instead of selector?

Also, given that I can guarantee that tr will be an immediate child of the table, would the performance improve above?

$("#MyTable>tr")

      

+2


source to share


2 answers


$("#MyTable > tr")

may not work as you must have either thead / tfoot or tbody as a direct child of the table. I think ff / chrome etc. Will add a tbody for you, so the selector should be



$("#MyTable > tbody > tr")

      

+3


source


Most likely the fastest of the three:

$("#MyTable > tr")

      

since you are selecting the direct descendant of the element reference using the id, so the selection is pretty straight forward.

EDIT: @redsquare pointed out that the above will not work in Firefox and Chrome as these browsers will add a tbody element to tables.

Context selectors mostly convert to "finds", so the slowest of the first two is:

$("tr", "#MyTable");

      



since it converts to something like this before any choice happens:

$('#MyTable').find('tr');

      

Of course, it will probably be of great benefit to you to compare them yourself.

Here are some of the previously asked questions about SO:

+1


source







All Articles