style vs cssText vs setAttribute (v8)

Revision 8 of this benchmark created on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>
    #test div {
        float:left;
        }
</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]
    var styles = { width:  i%10
                 , height: i%10
                 , background: colors[++count%colors.length]
                 };
    for (var s in styles) {
        if (!styles.hasOwnProperty(s)) continue;
        el.style[s] = styles[s];
    }
}
ready
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
}
ready
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)
}
ready
jQuery.css
for (var i=0; i<100; i++) {
    elems[i].css({ width:  i%10
                 , height: i%10
                 , background: colors[++count%colors.length]
                 })
}
ready

Revisions

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