CSS Style - Case 2

JavaScript performance comparison

Revision 3 of this test case created by Cong Liu

Preparation code

<div id="foo">
  Bar
</div>
<style>
  .my-style { background-color: red; width: 200px; }
</style>
      
<script>
Benchmark.prototype.setup = function() {
  var foo = document.getElementById('foo');
  
  function test1() {
    foo.style.backgroundColor = 'red';
    foo.style.width = '200px';
  }
  
  function test2() {
    foo.style.cssText = 'background-color: red; width: 200px;';
  }
  
  function test3() {
    var list = foo.className.split(' ');
    var pos = list.indexOf('my-style');
    if (pos === -1) foo.className += ' my-style';
  }
  
  function test4() {
    foo.classList.add('my-style');
  }
  
  function bench(func) {
    for (var i = 0; i < 500; i++) func();
  }

};

Benchmark.prototype.teardown = function() {
  foo.style.cssText = foo.className = '';

};
</script>

Preparation code output

<div id="foo"> Bar </div> <style> .my-style { background-color: red; width: 200px; } </style>

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
foo.className
bench(test3)
pending…
foo.classList
bench(test4)
pending…
foo.style.cssText
bench(test2)
pending…
foo.style.*
bench(test1)
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.

0 Comments

Bar