style vs cssText vs setAttribute (v9)

Revision 9 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]
    el.style.marginTop  = (i%10)+"px"
    el.style.height = (i%10)+"px"
}
ready
cssText
if (!cssText) {
    Benchmark.abort()
}

for (var i=0; i<100; i++) {
    el = elems[i][0]
    text = 'marginTop:'      +(i%10)+'px;' 
         + 'height:'     +(i%10)+'px;'

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

    el.setAttribute("style", text)
}
ready
jQuery.css
for (var i=0; i<100; i++) {
    elems[i].css({ marginTop:  i%10
                 , height: i%10
                 })
}
ready

Revisions

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