style vs cssText vs setAttribute

JavaScript performance comparison

Test case created by rmaksim

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>
    #test div {
        float:left;
        }
</style>

<div id="test"></div>

      
<script>
Benchmark.prototype.setup = function() {
  var $test = $("#test")
    , cssText = typeof(document.createElement("div").style.cssText) != "undefined"
    , elems = []
    , colors = "#f88 #8f8 #88f #ff8 #8ff #f8f".split(" ")
    , el
    , text
    , count = 0
  
  test.innerHTML = ""
  
  for (var i=0; i<100; i++) {
      var el = $("<div>")
      elems.push(el)
      $test.append(el)
  }

};
</script>

Preparation code output

<style> #test div { float:left; } </style> <div id="test"></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
for (var i=0; i<100; i++) {
    el = elems[i][0]
    el.style.width  = (i%10)+"px"
    el.style.height = (i%10)+"px"
    el.style.background = colors[++count%colors.length]
}
pending…
cssText
if (!cssText) {
    Benchmark.abort()
}

for (var i=0; i<100; i++) {
    el = elems[i][0]
    text = 'width:'      +(i%10)+'px;' 
         + 'height:'     +(i%10)+'px;'
         + 'background:' +colors[++count%colors.length]

    el.style.cssText = text
}
pending…
setAttribute
for (var i=0; i<100; i++) {
    el = elems[i][0]
    text = 'width:'      +(i%10)+'px;' 
         + 'height:'     +(i%10)+'px;'
         + 'background:' +colors[++count%colors.length]

    el.setAttribute("style", text)
}
pending…
jQuery.css
for (var i=0; i<100; i++) {
    elems[i].css({ width:  i%10
                 , height: i%10
                 , background: colors[++count%colors.length]
                 })
}
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