tamakisquare
tamakisquare

Reputation: 17077

How does jQuery selection work behind the scene?

Which one of the following selectors has better performance, if not the same

  1. $('#location_form input#id_name')
  2. $('#id_name')

I often have questions like the above pop up in my mind. I can't really answer them because I lack the knowledge on how selection work behind the scene.

My asks:

  1. answer/opinions to the question above
  2. references that explain how jQuery selection work behind the scene
  3. do all javascript frameworks work in the same way as jQuery when it comes to selection?

Thanks a bunch.

Upvotes: 4

Views: 370

Answers (2)

Korvin Szanto
Korvin Szanto

Reputation: 4511

With your selectors, the latter is faster, as jQuery determines you only want to select by ID and returns document.getElementByID: https://github.com/jquery/jquery/blob/master/src/core.js#L145-165

Here is the full source code: https://github.com/jquery/jquery/blob/master/src/core.js#L78-188

Upvotes: 3

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

As usual, "it depends". For a trivially small document, there's not much difference.

For a larger document, #1 can have much better performance, because it limits the search to descendants of the element with the id of 'location_form', while #2 would search the entire document.

See http://api.jquery.com/category/selectors/ and more specifically, http://api.jquery.com/descendant-selector/

Upvotes: 3

Related Questions