Premasagar Premasagar - 11 days ago 7
CSS Question

Rendering performance: style attributes or classnames and stylesheet rules?

I'm building a data visualisation, and the rendering performance is critical. My question would be relevant to bog-standard HTML, though I happen to be using SVG, with JavaScript.

OK, a hypothetical scenario: say I have 10,000 DOM nodes with a

background-color
of "
red
", and 10,000 DOM nodes with a
background-color
of "
green
". Each node is created by a JavaScript loop. I could either:


  1. Set a
    style
    attribute on each node, specifying the
    background-color
    of the node:
    <element style="background-color:red;"/>

  2. Set a
    class
    attribute on each node, and then reference that class in an inline style or external stylesheet:

    <head><style>.foo {background-color:red;}</style></head>


    <body><element class="foo"/></body>



The performance of downloading the code is not at all important here - I'm only interested in the browser's rendering performance. I'm also quite aware that style attributes are not usually so useful or semantic in day-to-day website development, but I have a specific use case here.

I am interested in logical answers, but it'd be really useful to hear from anyone has actually tested this or read about someone else's tests (I've searched for information, but found nothing specifically on this).

Thanks for your help!

Answer

I've created a performance benchmark for this: http://jsperf.com/style-element-vs-attr

From initial tests in Firefox and Chrome, it looks like it's around three times as fast to create and render elements that use classNames, rather than style attributes. I was quite surprised by that - I wasn't sure, but expected the opposite.