Question

I have a situation where I'm wondering what the best approach is performance-wise.

I have a class name, let's call it .class-test. I also have a cached element, $body.

I can either retrieve the .class-test element by:

$('.class-test')

or by

$body.find('.class-test')

In a worst-case scenario, does one of these approaches win out over the other? Also, if someone could describe what is being done under the hood by the second approach that would be great (i.e. I know that .find defers to Sizzle, but if the element is cached does it already have a tree of its DOM elements stored, then it only needs to traverse that sub-tree to find the class? or is that tree only built as-needed?).

Was it helpful?

Solution

The difference is how many times you dip in the DOM pool so to speak. In the first query, jQuery will search from within the document( top level ) and travel down in to the DOM tree checking every level till it gets to the very end and then returns all of the matching elements.

In the second option, you specify the starting point, so instead of starting at the very top and working its way down you are starting at the body element. In this particular case you are only going one level lower but here is the real plus, since you have the body cached, jquery doesn't have to find that it can just reference the cached element.

When you get deeper into the DOM tree this can be a big time saver. You can save 10s to 100s of level checks. And although you wont notice this much for small sites, one day you may be working with enterprise level code bases where these performance gains will be very beneficial to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top