Clustered id rendering speed vs class

8

Some time ago I saw some tests to render CSS rendering using id to be faster than rendering using class , due to the amount of id is often lower in the document in relation to the number of classes (one of the tests you can check in this table - text in English).

Even though the difference being almost imperceptible from one selector to another I had a question as to whether rendering would be faster using grouping of id (with comma) or class when comparing large amounts of elements (1000 or +).

Ex. (like DryCSS):

<div id="teste-1"></div>
<div id="teste-2"></div>
<div id="teste-3"></div>

#teste-1, #teste-2, #teste-3 {
  border: 1rem solid transparent;
}

vs (conventional):

<div class="teste"></div>
<div class="teste"></div>
<div class="teste"></div>

.teste {
    border: 1rem solid transparent;
}

I was curious about the possible results and would like to know if does anyone know of a test tool whose I can compare the rendering between the two examples? And based on fundamentals, which of the two forms is faster? (taking into account the data described above).

NOTE: Doubt may seem silly, but it has a unique and specific goal for knowledge about rendering speed, so please avoid tips related to maintenance, scalability, document size and reuse as well as opinion id in CSS, I am aware of each of these points, my interest is only to know about the performance of the two selectors in the proposed situations.

    
asked by anonymous 17.11.2015 / 18:59

2 answers

5

Tool

Google Chrome had a CSS profiler , but this was removed because it is considered that CSS performance today is reasonably good for cases that were slow a few years ago, so simply this type of optimization is something that is not worth investing.

However, you can still see the time that styles are interpreted and recalculated for the page using the developer tool timeline.

By accessing the Timeline tab of the developer tool, start the capture by clicking the ball in the upper left corner, reloading the page being tested, and then click the ball again to finalize the data capture. Leave JS Profile checked.

Parse Stylesheet will give you the time it took for the browser to interpret the styles and > Recalculate style the time it took to apply the style.

See the example below:

Interpretingtheresults

Inthefigure,weseethatthestylesheetall.cssofthispagetook%of%millisecondstobeinterpreted.Nextthereisanotherspecificstylesheetformoderators.:)

Afterthesheetsareprocessed,anumberofstylecalculationeventsoccur,butunfortunatelytheydonotcontaintheinformationofwhichrulestheyareapplying.

Foramoreeffectivetest,itwouldbenecessarytoisolatethestylestomakesuretheyarerunning.Itisamanualwork,butwouldallowcomparisonstobemade.

Ontheotherhand,comparingtimesbetweenspecificselectorsdoesnotmakemuchsensebecauseofseveralfactors,including:

Implementationdependency

Eachbrowseranditsdifferentversionscanbeoptimized(ornot)inverydifferentways.

ThinkofCSSselectorsasacontract,anAPI,wherethereisnoguaranteeofhowtheimplementationismadeorevenmodified.

Possibleoptimizations

IfIweretoimplementamechanismtoapplyastylesheetintheDOMIwouldnotalwaysgothroughtheselectorselectorandforeachofthem,lookfortheelementsintheDOM,traversingthecountlesstreetimes.

First,Iwouldsaveid'sandclassesonmapssothataccesswasmadeinrelativelyconstanttimeregardlessofthenumberofelements.Idonotknowhowthisisactuallydoneineverybrowser,butIwillassumethatdevelopersarenowusingunsuitabledatastructures,scrollingthroughlistsortreesunnecessarilyatalltimes.

Second,evenincaseswhereitisnecessarytogothroughtheDOM,youcoulduseapatternlikeVisitorandapplymultiplestylesatthesametimeinbatch,sototaltimetoapplytwoselectorstogetherwasmuchlessthanthesumofthetimeofapplyingthetwoseparately.

Considerationoftotaltime

It'snotjustthetimetoapplyaselectorthatcounts.Asintheexampleabove,itisnecessarytoconsiderthestylesheetinterpretationtime.

Probablytheinterpretationofmanyindividualid'swilltakeamuchlongertimethantheinterpretationofasingleclass.

Inaddition,ifthebrowserhassomesortofcacheordatastructurelikethemapIdescribedabove,retrievingthelistofelementsthatcontainagivenclasscanbemuchfasterthanqueryingathousandtimesthemaplookingforid's

Considerations

First,whenawebsiteneedsoptimization,weshouldfirstlookatwhatcausesthegreatestimpactandforgetaboutpossiblemicro-optimizations.

Inthemulti-browserdevelopertool,youcaneasilyfindoutwhicheventsareslowerandleavetheuserblockedforlongerandthenlookforthecause.Here'sanexampleofanotherChromechartshowingthetimeofeachpageloadevent:

Second, almost never rely on performance claims that are based on ever-changing implementation details. Of course, there may be specific cases where we run into bugs or bizarre behavior and we need to work around the situation in some way. However, it is more appropriate to treat them as temporary solutions and not try to turn them into good practices.

    
18.11.2015 / 03:13
0

Good day in this link has a good specification on the speed of css rendering encompassing ids , classes , tags and universal.

link

In short, the order from the most efficient to the smallest is:

  • ID's
  • Classes
  • Tags
  • Universal
  

It is worth remembering that the performance difference between these elements usually has very low values imperceptible in a real situation

Summary of Mozilla recommendations

  • Avoid universal rules
  • Do not qualify ID rules with classes or tag names
  • Do not qualify class rules with tag names
  • Use the most specific category possible
  • Avoid the descending selector
  • Tag Category Rules should never contain a child selector
  • Question all uses of the child selector
  • Count on inheritance
  • Use style sheets with scope

How to Use Grouped Ids vs Classes

Based on the answer of an equal question in the SO in English and that makes perfectly sense for me

link

Translation:

There is no measurable difference between the two and as the purpose of the class is to duplicate the same style for multiple elements, it is semantically correct to use a class.

The only case where it pays to worry about the difference between the two is when you use javascript to select elements by ID or class, and even then only when we are talking about hundreds of elements.

If you do not get to this point, then the performance you get is lost by the extra kilobytes in your css that increase page load time.

In neither case will it impact your performance perceptibly.

And for your own good, use classes so you do not have to update your selectors every time you add a new element.

    
18.11.2015 / 02:07