New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Replace getElementsByTagName(tag)[0] with querySelector(tag) #6380
Comments
I'd be happy to pick up and complete this change if considered appropriate. |
Hi @alvaromontoro, thanks a lot for raising the issue. JS selectors performance is always an odd mishmash of different results. I created an example on jsperf.com and ran it with Firefox 74: and Chrome 80: In both browser we can see that I imagine is the same for When the selector is a generic tag though, things change a little. Firefox 74: Chrome 80: So, with superficial benchmarking, seems that For curiosity I also tried with Firefox 74: Chrome 80: I search on the internet to find out if these numbers are real and found this article from 2010: Why is getElementsByTagName() faster than querySelectorAll()? It explains that The article from 2010 explains it like this:
Basically the underlying data structure is more costly to build in the case of My suggestion would be to go in this order:
I learned a lot researching this @alvaromontoro, thank you! |
@rhymes thank you for sharing the research. It is really interesting ( |
@alvaromontoro please do! We've learned how faster |
@rhymes is this issue stale? I can go ahead and make the PR if no one else will :) |
@icncsx thank you! I'll take a look! |
I'm going to close this as I think it has been addressed by #8315 - Let me know otherwise @alvaromontoro and @icncsx |
This is not a problem, it would be more of a refactoring/performance improvement task.
In different parts of the repo, we can find the function
getElementsByTagName
used in this way:Using
getElementsByTagName
in such a way would be inefficient as it is searching the whole document looking for the tag (in the problematic cases "head" or "body" which should only appear once in the page), creating a list, and then accessing only the first element of that list. WhilequerySelector
would return the first element that fulfills the selector.The suggestion would be, instead of doing:
we could do this:
I considered that not using
querySelector
was due to the project aiming for some specific browser support. But there are other parts of the codebase which usequerySelector
.Here is a list of all the places where
getElementsByTagName
is used. Notice that not all of them would necessarily require this change.The text was updated successfully, but these errors were encountered: