CSS Selectors Performance, DOM Parsing

My question is about starting a DOM parsing, I would like to know why it is faster to use the CSS identifier selector than the class selector. When you need to analyze the DOM tree again and what tricks and performance improvements I should use ... also, someone told me that if I do something like

var $p = $("p"); $p.css("color", "blue"); $p.text("Text changed!"); 

instead

 $("p").css("color", "blue"); $("p").text("Text changed!"); 

improves performance, is this true for all browsers? Also, how do I know if my DOM tree has been reprocessed?

+6
source share
3 answers

Well, the #id selector is faster than the class selector because: (a) there can only be one element with a given id value; (b) browsers can contain an id -> element map, so the #id selector can work as fast as viewing a single map.

Further, the first option proposed above is definitely faster because it avoids the second search, thereby reducing the total search time based on the selection by 2 times.

Finally, you can use the “Chrome Developer Tools” Profiler selector (in the Profiles panel) to determine how long the browser takes to process the selectors on your page (match + apply styles to the corresponding elements.)

+10
source

I urge you to do your own performance tests when you have doubts. You can get more information on how to do this here: How do you test JavaScript performance code? . Once you have tested the performance yourself, you will never forget the results.

In particular, executing the $() function on a particular jquery selector should get the corresponding DOM nodes. I don’t know exactly how this works, but I assume that this is a combination of document.getElementById() , document.getElementsByTagName() and others. This has a processing cost, no matter how small it can be, if you call it only once and then reuse it, you save some processing time.

+1
source

The ID selector is faster than the class selector because there is only one element with an identifier, but many elements can share a class and need to be looked up.

The code below will uselessly parse the DOM twice, so of course it will be slower:

 $("p").css("color", "blue"); $("p").text("Text changed!"); 
+1
source

Source: https://habr.com/ru/post/913431/


All Articles