Selectors: be specific on the right side?

Learn jQuery :

Be specific on the right side of your selector and less specific on the left.

// Unoptimized: $( "div.data .gonzalez" ); // Optimized: $( ".data td.gonzalez" ); 

I understand the part on the left side, but what about the part that will be specific to the right size? How true is this in modern browsers? As far as I know, the Sizzle engine is not used in modern browsers. Let us change our “non-optimized” example to this, including the fact that we need to be “specific” on the right side by deleting the div :

 // Unoptimized modification: $( ".data .gonzalez" ); 

For our “optimized” example, we would have (for modern browsers):

  • Call queryselectorall on .data
  • Set getElementsByTagName to td from the result set from step 1.
  • Call queryselectorall for .gonzales from the result set from step 2

vs. our example of a "non-optimized modification":

  • Call queryselectorall on .data
  • Call queryselectorall for .gonzales with a result step of 1

Basically, we skip step 2. So it won’t:

 $( ".data .gonzalez" ); 

faster than:

 $( ".data td.gonzalez" ); 

Bringing the principle "be specific in the right size of your selector" obsolete for modern browsers?

+6
source share
1 answer

Using this HTML:

 <div class="data"> <table> <tr> <td class="gonzalez">test1</td> <td>test2</td> <td class="gonzalez">test3</td> </tr> </table> </div> 

Firefox 43:

$("div.data .gonzalez"); , $(".data td.gonzalez"); and $(".data .gonzalez"); equal (+/- 84866 operation / sec).

Chrome 47:

$(".data .gonzalez"); is the fastest (+/- 166496 operation / second).

$("div.data .gonzalez"); and $(".data td.gonzalez"); slightly slower (+/- 163243 operation / second).

IE 11:

$(".data .gonzalez"); is the fastest (+/- 55015 operation / second).

$("div.data .gonzalez"); and $(".data td.gonzalez"); slightly slower (+/- 42,490 operations per second)

Opera 34:

$(".data .gonzalez"); and $(".data td.gonzalez"); are the fastest (+/- 148887 operations / second).

$("div.data .gonzalez"); slightly slower (+/- 135785 operations per second)

Safari 5:

$("div.data .gonzalez"); , $(".data td.gonzalez"); and $(".data .gonzalez"); equal (+/- 63 560 operations / sec).

I created a test here: http://jsperf.com/compare-selector

0
source

All Articles