Is it faster to traverse the DOM from a cached selector than to find an ID'd element in the DOM?
Asked Answered
B

1

3

There are a lot of questions about whether or not finding an element is faster via class or id or some other selector. I'm not interested in that. I want to know if you have:

var link = $(this); //let's say you're in a click handler

Is it faster to find the container by doing

var container = link.closest('.container'); //assume container is .container

or

var container = $('#mycontainer'); //assume same element as above

I'm asking this question not just for the particular scenario above (ok, well, yes, for this scenario too) but for cached traversal vs. creating a fresh jQuery object that has an ID. I notice in a lot of my code I tend to do the former method (since it can lend itself to being more dynamic), but I was always curious if it was faster to do it the latter way.

Thanks

Buxton answered 3/5, 2012 at 4:8 Comment(3)
my suspicion is that the latter is faster, but did you test it? It would be pretty easy to knock up a test harness...Eustacia
I'm not sure if this information is outdated and corrected with the most recent iterations of jQuery, but I'm pretty sure that .closest() is relatively slower than other alternatives.Tradescantia
i actually created a jsperf: jsperf.com/cached-dom-traversal-vs-new-id-selection looks like ID is definitely the fastest, finding by class is next.Buxton
H
2

I would think that, cached selector or not, it would be faster to use the id selector. The ID selector is pretty much a direct dictionary lookup vs the cached/closest combination which is like a dictionary lookup, followed by a tree traversal.

http://jsperf.com/traverse-from-cached-selector-vs-id-selector

The fastest lookup would be done with the native documentGetElementById function.

var container = $(document.getElementById('MyContainer'));
Handicap answered 3/5, 2012 at 4:22 Comment(2)
it looks like traversing the tree is generally slower, which makes me wonder how good it is to use a cached object to then traverse from...Buxton
When it comes to traversing, I generally use cached objects to find collections of children elements. i.e. $cachedObject.find('.untoggled-children').toggle().toggleClass('untoggled-children toggled-children'); But when it comes to finding a single element, that has an id, I will always use $(document.getElementById('myid')).Handicap

© 2022 - 2024 — McMap. All rights reserved.