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:
style
attribute on each node, specifying the background-color
of the node: <element style="background-color:red;"/>
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!
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.
I would be extremely surprised if there is a significant difference (and even more surprised if it ever mattered) but if there was one it would be in IE so bench that.
That said, the conditions you are testing are so edge case that I do not think you should be abusing your markup to attain a small-to-insignificant performance benefit in the event that inline was faster. Class based CSS is immeasurably better for the purposes of development and maintenance and semantics and you should avoid inline styles at all costs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With