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

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

问题描述

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



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



现有证据





这是通用的声音,问题很多,当质疑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个元素不< c $ c> 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有意义的限制是

$。 b $ b

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

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天全站免登陆