Granted, this is an old question, but stumbled across this & felt like weighing in. One big note ahead of time, which I don't think anyone else delved into, is: those two statements aren't technically synonymous. This may explain the general performance difference.
The easiest example of this is actually YouTube. If you go to any video, you'll find that they actually repeat the ID, #content
. In the first video I tried, after loading the comments section, document.querySelectorAll("#content")
actually returned about 20 elements. This is not to standard, and the W3's HTML Validator will actually tell you this is invalid HTML. However, browsers still permit this, rather than straight-up rejecting or modifying the HTML.
If your site had repeated usages of #divContentList
, your statement would return all of the article elements from within all of them; whereas your coworker's would only return articles nested within the the first instance of #divContentList
that it found. This may explain why your coworkers appears to generally be faster (see below). And like most people've already pointed out, replacing his/her first querySelector
with getElementById
would likely be even faster across all browsers.
Beyond that, I agree with the general idea that, "if you want to know the performance of something: just measure it." but be careful with how you construct your tests. Here's an example where the JS engine optimized out the actual test case. My advice is always test within the context of your actual use-case. There have been threads talking about how element.querySelector
can actually be slower than document.querySelector
; however, from brief recent testing, I could not replicate this.
Using IDs / classes like #sidebar
and .question-hyperlink
on this page itself, in all cases document.querySelector('<ID>').querySelectorAll('<CLASS>');
outperformed document.querySelectorAll('<ID> <CLASS>');
.
However, and I feel like this is critical, the difference was never more than ~10-20%. At a certain point the question becomes, "is the trade-off between readability / writeability vs performance worthwhile". If you're only running this statement one or two times, the difference is likely in the order of microseconds. For a general use-case, either your original statement or your coworker's would be fine.
And one final note,
I don't think his solution is the best in speed performance and it search the element twice
If you felt like a bit of reading, you could look into how browsers actually implement these lookup methods for webpages. Looking at the Firefox source, what you'll find is "getElementById" uses a hashtable lookup, which makes it nearly instantaneous to find a result. The implementation will vary between vendors, which is why it can be important that you test your site on many different browsers.