style vs cssText vs setAttribute (v5)

Revision 5 of this benchmark created on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>
    #test { overflow: hidden; width: 100%; height: 100%; }
    #test div {
        float:right;
        width: 10px;
        height: 10px;
        }
</style>

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

Setup

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)
    }

Test runner

Ready to run.

Testing in
TestOps/sec
style
for (var i=0; i<100; i++) {
    el = elems[i][0]
    el.style.width  = i+"px"
    el.style.height = i+"px"
    el.style.background = colors[++count%colors.length]
}
ready
cssText
if (!cssText) {
    Benchmark.abort()
}

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

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

    el.setAttribute("style", text)
}
ready
jQuery.css
for (var i=0; i<100; i++) {
    elems[i].css({ width:  i
                 , height: i
                 , background: colors[++count%colors.length]
                 })
}
ready
style with temp variable
for (var i=0; i<100; i++) {
    var style = elems[i][0].style
    style.width  = i+"px"
    style.height = i+"px"
    style.background = colors[++count%colors.length]
}
ready
display: none
$test.hide();
for (var i=0; i<100; i++) {
    var style = elems[i][0].style
    style.width  = i+"px"
    style.height = i+"px"
    style.background = colors[++count%colors.length]
}
$test.show();
ready

Revisions

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