gpt4 book ai didi

css - CSS 选择器更改后性能显着下降

转载 作者:行者123 更新时间:2023-12-02 04:44:03 28 4
gpt4 key购买 nike

我在一个相当复杂的 Web 应用程序中对一些 SASS 选择器做了一个小改动,发现性能显着下降。使用 Chrome 的时间轴功能分析页面时,“重新计算样式”(我假设在 DOM 操作后重排页面)的实例从大约 1 毫秒变为大约 100 毫秒,并且影响这些样式重新计算的元素计数从大约 10 变为大约 1500。

是什么让这个选择器变得如此邪恶?以后要注意什么,才不会重蹈覆辙?

原始 CSS(快速):

.button-group .button:not(:last-of-type) {
margin-right: -1px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.button-group .button:not(:first-of-type) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}

修改后的 CSS(非常慢):

.button-group > :not(:first-of-type) .button, .button-group > :not(:first-of-type).button {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.button-group > :not(:last-of-type) .button, .button-group > :not(:last-of-type).button {
margin-right: -1px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}

最佳答案

为了分解它,我将忽略 .button-group,因为它在两者中是相同的,不会影响任何东西。

在第一个示例中,您选择了每个 button 类。浏览器针对搜索类进行了优化,因此通常速度非常快。然后,您使用 not(:last-of-type) 修饰符,它速度较慢,但​​并不重要,因为池已经仅限于 button 类。

在第二个示例中,您首先搜索 :not(:first-of-type),它对 .button-group 的每个子级执行昂贵的操作.虽然使用直接子运算符 (>) 将有助于限制该池,但它的元素数量可能仍然比第一个示例更多。我不太确定你想用 .button, &.button 做什么,但无论哪种方式,该操作都不是很昂贵,因为你只是按类选择并且你已经已经限制了池。

因此,一般来说,您希望从成本最低的操作转到成本最高的操作,以便对尽可能少的元素进行密集计算。

旁注,我认为您在第二个示例中的 .button 之后缺少逗号。


编辑:只是想指出您的两段代码编译后的区别。

首先:

.button-group .button:not(:last-of-type)

第二个:

.button-group > :not(:first-of-type) .button, 
.button-group > :not(:first-of-type).button {

如您所见,第二个要进行的内容要多得多。这可能是它变慢的原因,尽管我现在正在检查以确保 not 的顺序有影响。

关于css - CSS 选择器更改后性能显着下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34907757/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com