哪些CSS选择器或规则可以显着影响前端布局/渲染性能在现实世界中? [英] Which CSS selectors or rules can significantly affect front-end layout / rendering performance in the real world?

查看:180
本文介绍了哪些CSS选择器或规则可以显着影响前端布局/渲染性能在现实世界中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否值得担心CSS呈现效果?或者,我们不必担心CSS的效率,只是专注于编写优雅或可维护的CSS?



这个问题旨在为前端开发者提供一个有用的资源,部分CSS可能实际上对设备性能有重大影响,以及哪些设备/浏览器或引擎可能会受到影响。这不是关于如何编写优雅或可维护的CSS的问题,它纯粹关于性能(虽然希望这里写的内容可以告诉更多关于最佳实践的一般文章)。



现有证据



Google Mozilla 已撰写有关编写高效CSS的指南, CSSLint的一组规则包括: p>


避免使用看起来像正则表达式的选择器
..
不使用复杂的等式运算符来避免性能惩罚


但没有一个提供任何证据(我可以找到)这些影响。



css-tricks.com有关高效CSS的文章认为(在概述了效率最佳实践的负载后),我们应该不...牺牲语义或可维护性的高效CSS 这些天。



完美杀毒博文建议 border-radius box-shadow 渲染的顺序比简单的CSS规则慢。这在Opera的引擎中是非常重要的,但在Webkit中是微不足道的。此外,粉碎杂志CSS基准发现CSS3显示规则的呈现时间并不显着,并且比使用图片呈现等效效果快得多。



了解您的移动测试了各种移动浏览器,发现他们都渲染CSS3的速度相当不明显(12毫秒),但看起来他们做了测试一个电脑,所以我们不能推断任何关于手持设备如何使用CSS3的一般性。



很多 文章在互联网上如何编写高效的CSS。但是,我还没有找到任何全面的证据,认为CSS实际上对网站的呈现时间或快照有显着的影响。



背景



回来,我要试试科学http://brightgreenscotland.org/wp-content/uploads/2010/09/stand-back-Im-going-to- try-science.png



我为这个问题提供了赏金,尝试使用SO的社群力量创建一个有用的研究资源。 p>

解决方案

这里的第一件事是:渲染引擎你使用?



那么,通用的听起来很重要,当质疑CSS渲染的效率/选择。例如,假设您的CSS文件中的第一个规则是:

  .class1 {
/ class1look fancy * /
}

所以当一个非常基本的引擎看到因为这是第一条规则),它会查看DOM中的每个元素,并检查每个元素中是否存在 class1 。更好的引擎可能将类名映射到DOM元素列表,并使用类似hashtable的方法来进行有效的查找。

  .class1.class2 {
/ * make元素与class1和class2看起来更加奇特* /
}

我们的例子基本引擎将去重新访问DOM中的每个元素寻找这两个类。一个cleverer引擎会比较 n('class1') n('class2')其中 n(str)是类中 str 的DOM中的元素数,取最小值;假设是 class1 ,然后传递所有元素 class1 寻找具有 class2 以及。



无论如何,现代引擎是聪明的(比上面讨论的例子更聪明),闪亮的新处理器可以做数百万(数千万)的操作。你的DOM中有几百万个元素是不太可能的,所以任何选择( O(n))的最坏情况下的性能不会太差。 / p>




更新:

要获得一些实际的说明性证明,测试。首先,要了解平均有多少DOM元素可以在现实世界的应用程序中看到,让我们来看看一些热门网站的网页有多少元素:



Facebook:〜1900个元素(在我的个人主页上测试)。

Google :〜​​340个元素。
Google:〜950个元素(在搜索结果页上进行测试)。

Yahoo! :〜​​1400元素(在主页上测试)。
$ $ b $ Stackoverflow:约680个元素(在问题页面上测试)。
$ $ b AOL:〜1060个元素(在主页上测试)。
$ $ b $ 维基百科:约6000个元素,其中2420个不是 span anchors (测试于关于Glee的维基百科文章)。

Twitter:约270个元素(在主页上测试)。



总之,我们得到的平均值约为1500元素。现在是时候做一些测试。对于每个测试,我生成1500 divs (对于一些测试,嵌套在一些其他 divs






测试



和元素都是使用PHP生成的。我已上传我使用的PHP,并创建了一个索引,以便其他人可以在本地测试:小链接






结果:



每个测试在三个浏览器上执行5次(报告平均时间): Firefox 15.0 (A), Chrome 19.0.1084.1 (B), Internet Explorer 8

  ABC 
1500类选择器(.classname)35ms 100ms 35ms
1500类选择器, div.classname)36ms 110ms 37ms
1500类选择器,更具体(div div.classname)40ms 115ms 40ms
1500 id选择器(#id)35ms 99ms 35ms
1500 id选择器,更多特定(div#id)35ms 105ms 38ms
1500 id选择器,更具体的(div div#id)40ms 110ms 39ms
1500类选择器,带有属性(.class [title =ttl]) 45ms 400ms 2000ms
1500类选择器,更复杂的属性(.class [title〜=ttl])45ms 1050ms 2200ms






类似的实验:



显然其他人进行了类似的实验;这个也有一些有用的统计资料:小连结



底线:

除非你关心在渲染时保存几个毫秒(1ms = 0.001s),否则不要过多思考。另一方面,避免使用复杂选择器来选择元素的大子集是一个好的习惯,因为这可以产生一些显着的差异(从上面的测试结果可以看出)。所有常见的CSS选择器在现代浏览器中速度相当快。



假设您正在建立一个聊天网页,并且您想为所有邮件设定样式。你知道每个消息都在 div 中,它有 title ,嵌套在 div 与类 .chatpage 正确使用 .chatpage div [title] 选择邮件,但是效率也不高。






这是一个简单的,更易于维护的,更高效的给所有的邮件一个类,花哨的一线结论:



任何在是的,这CSS有意义的限制之内是


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 maintainable CSS instead?

This question is intended to be a useful resource for front-end developers on which parts of CSS can actually have a significant impact on device performance, and which devices / browsers or engines may be affected. This is not a question about how to write elegant or maintainable CSS, it's purely about performance (although hopefully what's written here can inform more general articles on best-practice).

Existing evidence

Google and Mozilla have written guidelines on writing efficient CSS and CSSLint's set of rules includes:

Avoid selectors that look like regular expressions .. don't use the complex equality operators to avoid performance penalties

but none of them provide any evidence (that I could find) of the impact these have.

A css-tricks.com article on efficient CSS argues (after outlining a load of efficiency best practices) that we should not .. sacrifice semantics or maintainability for efficient CSS these days.

A perfection kills blog post suggested that border-radius and box-shadow rendered orders of magnitude slower than simpler CSS rules. This was hugely significant in Opera's engine, but insignificant in Webkit. Further, a smashing magazine CSS benchmark found that rendering time for CSS3 display rules was insignificant and significantly faster than rendering the equivalent effect using images.

Know your mobile tested various mobile browsers and found that they all rendered CSS3 equally insignificantly fast (in 12ms) but it looks like they did the tests on a PC, so we can't infer anything about how hand-held devices perform with CSS3 in general.

There are many articles on the internet on how to write efficient CSS. However, I have yet to find any comprehensive evidence that badly considered CSS actually has a significant impact on the rendering time or snappiness of a site.

Background

stand back, I'm going to try science http://brightgreenscotland.org/wp-content/uploads/2010/09/stand-back-Im-going-to-try-science.png

I offered bounty for this question to try to use the community power of SO to create a useful well-researched resource.

解决方案

The first thing that comes to mind here is: how clever is the rendering engine you're using?

That, generic as it sounds, matters a lot when questioning the efficiency of CSS rendering/selection. For instance, suppose the first rule in your CSS file is:

.class1 {
    /*make elements with "class1" look fancy*/
}

So when a very basic engine sees that (and since this is the first rule), it goes and looks at every element in your DOM, and checks for the existence of class1 in each. Better engines probably map classnames to a list of DOM elements, and use something like a hashtable for efficient lookup.

.class1.class2 {
    /*make elements with both "class1" and "class2" look extra fancy*/
}

Our example "basic engine" would go and revisit each element in DOM looking for both classes. A cleverer engine will compare n('class1') and n('class2') where n(str) is number of elements in DOM with the class str, and takes whichever is minimum; suppose that's class1, then passes on all elements with class1 looking for elements that have class2 as well.

In any case, modern engines are clever (way more clever than the discussed example above), and shiny new processors can do millions (tens of millions) of operations a second. It's quite unlikely that you have millions of elements in your DOM, so the worst-case performance for any selection (O(n)) won't be too bad anyhow.


Update:

To get some actual practical illustrative proof, I've decided to do some tests. First of all, to get an idea about how many DOM elements on average we can see in real-world applications, let's take a look at how many elements some popular sites' webpages have:

Facebook: ~1900 elements (tested on my personal main page).
Google: ~340 elements (tested on the main page, no search results).
Google: ~950 elements (tested on a search result page).
Yahoo!: ~1400 elements (tested on the main page).
Stackoverflow: ~680 elements (tested on a question page).
AOL: ~1060 elements (tested on the main page).
Wikipedia: ~6000 elements, 2420 of which aren't spans or anchors (Tested on the Wikipedia article about Glee).
Twitter: ~270 elements (tested on the main page).

Summing those up, we get an average of ~1500 elements. Now it's time to do some testing. For each test, I generated 1500 divs (nested within some other divs for some tests), each with appropriate attributes depending on the test.


The tests

The styles and elements are all generated using PHP. I've uploaded the PHPs I used, and created an index, so that others can test locally: little link.


Results:

Each test is performed 5 times on three browsers (the average time is reported): Firefox 15.0 (A), Chrome 19.0.1084.1 (B), Internet Explorer 8 (C):

                                                                        A      B      C
1500 class selectors (.classname)                                      35ms   100ms  35ms
1500 class selectors, more specific (div.classname)                    36ms   110ms  37ms
1500 class selectors, even more specific (div div.classname)           40ms   115ms  40ms
1500 id selectors (#id)                                                35ms   99ms   35ms
1500 id selectors, more specific (div#id)                              35ms   105ms  38ms
1500 id selectors, even more specific (div div#id)                     40ms   110ms  39ms
1500 class selectors, with attribute (.class[title="ttl"])             45ms   400ms  2000ms
1500 class selectors, more complex attribute (.class[title~="ttl"])    45ms   1050ms 2200ms


Similar experiments:

Apparently other people have carried out similar experiments; this one has some useful statistics as well: little link.


The bottom line:

Unless you care about saving a few milliseconds when rendering (1ms = 0.001s), don't bother give this too much thought. On the other hand, it's good practice to avoid using complex selectors to select large subsets of elements, as that can make some noticeable difference (as we can see from the test results above). All common CSS selectors are reasonably fast in modern browsers.

Suppose you're building a chat page, and you want to style all the messages. You know that each message is in a div which has a title and is nested within a div with a class .chatpage. It is correct to use .chatpage div[title] to select the messages, but it's also bad practice efficiency-wise. It's simpler, more maintainable, and more efficient to give all the messages a class and select them using that class.


The fancy one-liner conclusion:

Anything within the limits of "yeah, this CSS makes sense" is okay.

这篇关于哪些CSS选择器或规则可以显着影响前端布局/渲染性能在现实世界中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆