2

I have a query like this:

$('#tabContainer li');

And JetBrains WebStorm IDE highlights it as an inefficient query. It suggests me to use this instead:

$('#tabContainer').find('li')

How can it be explained? Are there docs explaining such cases?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

3 Answers3

3

In this article, there is a part of specificity (Fourth point).

If you have $('#tabContainer li'), all li you have in the document wil be queried. Then each of those li would be checked to see if they have a parent #tabContainer.

To get it quicker, $('#tabContainer').find('li') can be used. The li would be searched in the #tabContainer, which is unique in the document.

But apparently, if you are selecting using an ID, there should not be much improvement in performance (from the answer on this question on SO which also talks about specificity).

Community
  • 1
  • 1
RRikesh
  • 14,112
  • 5
  • 49
  • 70
0

jQuery will translate the former expression into the latter. Therefore the only difference is some calling overhead within jQuery. It's negligible in my opinion.

But: $('#tabContainer').find('li') improves readability (at least for people who are not very familiar with the selector syntax) and I'd consider that a good reason to use it..

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
0

I believe the reasoning for the optimization is speed. Find can be extremely fast but it would not hurt to benchmark your particular use case. For instance, here is a test that uses a few possible variations similar to what you are trying to do.

http://jsperf.com/jquery-find-vs-context-sel/9

In this case find is extremely fast. Now, if you are only running that selection one time; it really does not matter which way you do it as long as it is easy to read/understand its intent.

ian.shaun.thomas
  • 3,468
  • 25
  • 40