3

Everybody states, that the * { ... } selector is very slow. But how slow is it really?

I always try to avoid it, but sometimes it's very useful. For example: * + h1 { margin-top 1em; }

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
buschtoens
  • 8,091
  • 9
  • 42
  • 60

1 Answers1

6

To put it very simply: the universal selector * is only as slow as there are elements on your page.

Since right-to-left matching browsers take each element and match it against all candidate rules, every element will match * just fine. It by itself doesn't harm performance, but if you have many elements in your page or a very complex DOM, that's where it allegedly gets slow, but even then it doesn't visibly degrade browser performance.

Even something like * + h1, for example, is reasonable, since if you want to take matching performance into account, then a right-to-left matching browser will test that selector only on h1 elements first, before checking if there's any element occurring before them (which really doesn't take much effort as * is basically a guaranteed match).

You may also wish to check out this answer of mine to a similar question about * + * (that's two universal selectors!).

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • If you get complaints about `* + h1` because of the `*`, then `h1:not(:first-child)` is equivalent. You can then decide whether you want to sacrifice microseconds of performance or entire browser userbases (IE7 and 8 don't support `:not()`). – BoltClock Sep 01 '12 at 15:23
  • Very good answer and thanks for that clever `h1:not(:first-child)`. – buschtoens Sep 01 '12 at 15:26