Why is there a performance problem with querySelector?

querySelector compared to getElement series. Why is there a performance problem? I don"t think there is a good answer on the Internet. Since there are performance problems, why is this method widely used in many libraries?

Mar.30,2022

feels like querySelector supports universal selector writing, while the getElemet (s) ByXXX series limits the types of selectors that can be used at the beginning, which results in the former having to parse the entire selector text completely (check for syntax errors in the process) and then look in the DOM tree, while the latter knows from the beginning that the selector text you gave it is not valid.


The elements and array of elements selected by the

querySelector selector are static, while the elements selected by getElement are dynamic.

static means that it will not change with the dom operation, and the dynamic dom will change with it

as for asking why many libraries are in use, it may be because it is convenient. After all, getElement has to choose many levels of both id and class, which is very troublesome. If you use querySelector, you can just use the css selector, which depends on which one you choose

.

theoretically, the optimized querySelector command should use the same code as the CSS selector in the rendering engine. As long as CSS is as fast as querySelector is, of course, this is only theoretical

.
Menu