Class vs. Style

JavaScript performance comparison

Test case created by Hakim El Hattab

Preparation code

<style>
  .one { background: red; width: 100px; height: 100px; }
  .two { background: blue; width: 50px; height: 50px; }
</style>
<div id="candidate"></div>
      
<script>
Benchmark.prototype.setup = function() {
  var candidate = document.getElementById('candidate');

};
</script>

Preparation code output

<style> .one { background: red; width: 100px; height: 100px; } .two { background: blue; width: 50px; height: 50px; } </style> <div id="candidate"></div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Style
candidate.style.background = 'red';
candidate.style.width = '100px';
candidate.style.height = '100px';

candidate.style.background = 'blue';
candidate.style.width = '50px';
candidate.style.height = '50px';
pending…
Class (setAttribute)
candidate.setAttribute('class', 'one');
candidate.setAttribute('class', 'two');
pending…
Style (setAttribute)
candidate.setAttribute('style', 'background: red; width: 100px; height: 100px;');
candidate.setAttribute('style', 'background: blue; width: 50px; height: 50px;');
pending…
Class (className)
candidate.className = 'one';
candidate.className = 'two';
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

6 Comments

Mathias Bynens commented :

Note that adding a class using .setAttribute() may not work in older IEs.

Marco Pivetta commented :

Well, never tested it before, but that really removes some doubts! :D Thank you for sharing! :)

Keegan Street commented :

Good to see that it is faster to set a class name than set inline styles!

James Williamson commented :

My only question is will the speed gain be offset by the additional weight the CSS will gain through the additional class definitions?

Thanks for setting this up...

Jonas Finnemann Jensen commented :

How about .classList.add and .classList.remove, I suppose they're close to className. But it would be awesome to include them, just for completeness.

Anyways, nice clear results :)

Chris commented :

This doesn't account for a large number of unused classes. Drop twitter bootstrap in the preparation code then give it a shot. Even if the classes aren't unused in the page any give reflow has to match against the css loaded. Not saying it will win just saying give it a fair match.