Which CSS selectors or rules can significantly affect front-end layout / rendering performance in the real world?

后端 未结 6 2160
情书的邮戳
情书的邮戳 2020-12-12 11:56

Is it worth worrying about CSS rendering performance? Or should we just not worry about efficiency at all with CSS and just focus on writing elegant or main

6条回答
  •  一整个雨季
    2020-12-12 12:47

    Most answers here focus on selector performance as if it were the only thing that matters. I'll try to cover some spriting trivia (spoiler alert: they're not always a good idea), css used value performance and rendering of certain properties.

    Before I get to the answer, let me get an IMO out of the way: personally, I strongly disagree with the stated need for "evidence-based data". It simply makes a performance claim appear credible, while in reality the field of rendering engines is heterogenous enough to make any such statistical conclusion inaccurate to measure and impractical to adopt or monitor.

    As original findings quickly become outdated, I'd rather see front-end devs have an understanding of foundation principles and their relative value against maintainability/readability brownie points - after all, premature optimization is the root of all evil ;)


    Let's start with selector performance:

    Shallow, preferably one-level, specific selectors are processed faster. Explicit performance metrics are missing from the original answer but the key point remains: at runtime an HTML document is parsed into a DOM tree containing N elements with an average depth D and than has a total of S CSS rules applied. To lower computational complexity O(N*D*S), you should

    1. Have the right-most keys match as few elements as possible - selectors are matched right-to-left^ for individual rule eligibility so if the right-most key does not match a particular element, there is no need to further process the selector and it is discarded.

      It is commonly accepted that * selector should be avoided, but this point should be taken further. A "normal" CSS reset does, in fact, match most elements - when this SO page is profiled, the reset is responsible for about 1/3 of all selector matching time so you may prefer normalize.css (still, that only adds up to 3.5ms - the point against premature optimisation stands strong)

    2. Avoid descendant selectors as they require up to ~D elements to be iterated over. This mainly impacts mismatch confirmations - for instance a positive .container .content match may only require one step for elements in a parent-child relationship, but the DOM tree will need to be traversed all the way up to html before a negative match can be confirmed.

    3. Minimize the number of DOM elements as their styles are applied individually (worth noting, this gets offset by browser logic such as reference caching and recycling styles from identical elements - for instance, when styling identical siblings)

    4. Remove unused rules since the browser ends up having to evaluate their applicability for every element rendered. Enough said - the fastest rule is the one that isn't there :)

    These will result in quantifiable (but, depending on the page, not necessarily perceivable) improvements from a rendering engine performance standpoint, however there are always additional factors such as traffic overhead and DOM parsing etc.


    Next, CSS3 properties performance:

    CSS3 brought us (among other things) rounded corners, background gradients and drop-shadow variations - and with them, a truckload of issues. Think about it, by definition a pre-rendered image performs better than a set of CSS3 rules that has to be rendered first. From webkit wiki:

    Gradients, shadows, and other decorations in CSS should be used only when necessary (e.g. when the shape is dynamic based on the content) - otherwise, static images are always faster.

    If that's not bad enough, gradients etc. may have to be recalculated on every repaint/reflow event (more details below). Keep this in mind until the majority of users user can browse a css3-heavy page like this without noticeable lag.


    Next, spriting performance:

    Avoid tall and wide sprites, even if their traffic footprint is relatively small. It is commonly forgotten that a rendering engine cannot work with gif/jpg/png and at runtime all graphical assets are operated with as uncompressed bitmaps. At least it's easy to calculate: this sprite's width times height times four bytes per pixel (RGBA) is 238*1073*4≅1MB. Use it on a few elements across different simultaneously open tabs, and it quickly adds up to a significant value.

    A rather extreme case of it has been picked up on mozilla webdev, but this is not at all unexpected when questionable practices like diagonal sprites are used.

    An alternative to consider is individual base64-encoded images embedded directly into CSS.


    Next, reflows and repaints:

    It is a misconception that a reflow can only be triggered with JS DOM manipulation - in fact, any application of layout-affecting style would trigger it affecting the target element, its children and elements following it etc. The only way to prevent unnecessary iterations of it is to try and avoid rendering dependencies. A straightforward example of this would be rendering tables:

    Tables often require multiple passes before the layout is completely established because they are one of the rare cases where elements can affect the display of other elements that came before them on the DOM. Imagine a cell at the end of the table with very wide content that causes the column to be completely resized. This is why tables are not rendered progressively in all browsers.


    I'll make edits if I recall something important that has been missed. Some links to finish with:

    http://perfectionkills.com/profiling-css-for-fun-and-profit-optimization-notes/

    http://jacwright.com/476/runtime-performance-with-css3-vs-images/

    https://developers.google.com/speed/docs/best-practices/payload

    https://trac.webkit.org/wiki/QtWebKitGraphics

    https://blog.mozilla.org/webdev/2009/06/22/use-sprites-wisely/

    http://dev.opera.com/articles/view/efficient-javascript/

提交回复
热议问题