!important 对性能有害吗? [英] Is !important bad for performance?
问题描述
我讨厌它们,它违背了 CSS 的级联特性,如果你不小心使用它们,你最终会陷入添加更多 !important
的循环中.
但我想知道它们对性能有害吗?
编辑
从(快速)回复中,我可以得出结论,它不会对性能产生(显着)影响.但很高兴知道,即使这只是作为劝阻他人的额外理由;)
编辑 2
BoltClock 指出,如果有 2 个 !important
声明,规范说它会选择最具体的一个.
它不应该对性能产生任何明显的影响.在
现在,您可以很容易地看到,在上述对象模型的情况下,解析器可以轻松标记受 !important
影响的规则,而不会产生太多后续成本.性能下降不是反对 !important
的好理由.
但是,可维护性确实受到了打击(正如其他答案所提到的),这可能是您反对它们的唯一论据.
I hate them, it defies the cascading nature of CSS, and if you don't use them with care you end up in a loop of adding more !important
.
But I want to know are they bad for performance?
EDIT
From the (fast) replies I can conclude it won't have a (significant) impact on performance.
But it's nice to know, even if it's just as an extra argument for discouraging others ;).
EDIT 2
BoltClock pointed out that if there are 2 !important
declarations the specs says it will pick the most specific one.
It shouldn't have any discernible effects on performance. Seeing Firefox's CSS parser at /source/layout/style/nsCSSDataBlock.cpp#572
and I think that is the relevant routine, handling overwriting of CSS rules.
It just seems to be a simple check for "important".
if (aIsImportant) {
if (!HasImportantBit(aPropID))
changed = PR_TRUE;
SetImportantBit(aPropID);
} else {
// ...
}
Also, comments at source/layout/style/nsCSSDataBlock.h#219
/**
* Transfer the state for |aPropID| (which may be a shorthand)
* from |aFromBlock| to this block. The property being transferred
* is !important if |aIsImportant| is true, and should replace an
* existing !important property regardless of its own importance
* if |aOverrideImportant| is true.
*
* ...
*/
Firefox uses a top down parser written manually. In both cases each CSS file is parsed into a StyleSheet object, each object contains CSS rules.
Firefox then creates style context trees which contain the end values (after applying all rules in the right order)
From: http://taligarsiel.com/Projects/howbrowserswork1.htm#CSS_parsing
Now, you can easily see, in such as case with the Object Model described above, the parser can mark the rules affected by the !important
easily, without much of a subsequent cost. Performance degradation is not a good argument against !important
.
However, maintainability does take a hit (as other answers mentioned), which might be your only argument against them.
这篇关于!important 对性能有害吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!