Stylesheet vs DOM manipulation JavaScript performance comparison

Preparation code < style type = "text/css" > .red { color :red} .green { color :green} </ style > < div id = "untouched" > This DIV is unchanged </ div > < div id = "touched" > This DIV needs to be manipulated </ div >

< script >

Benchmark. prototype . setup = function ( ) {

var sheet = ( function ( ) { var style = document .createElement( "style" ); style.appendChild( document .createTextNode( "" )); document .head.appendChild(style); return style.sheet; })(); function addCSSRule ( sheet, selector, rules, index ) { if ( "insertRule" in sheet) { sheet.insertRule(selector + "{" + rules + "}" , index); } else if ( "addRule" in sheet) { sheet.addRule(selector, rules, index); } } var elemPreselected = document .getElementById( "touched" );

} ;



Benchmark. prototype . teardown = function ( ) {

var elemPreselected = document .getElementById( "touched" ); elemPreselected.style.color = "" ; elemPreselected.className = "" ;

} ;

< / script >

Preparation code output <style type="text/css">.red{color:red}.green{color:green}</style> <div id="untouched">This DIV is unchanged</div> <div id="touched">This DIV needs to be manipulated</div>

Test runner Warning! For accurate results, please disable Firebug before running the tests. (Why?) Java applet disabled. To run the tests, please enable JavaScript and reload the page. Testing in Other 0.0.0 / Other 0.0.0 Test Ops/sec DOM Manipulation rewrite style text var elem = document .getElementById( "touched" ); elem.style.cssText = "color:red" ; elem.style.cssText = "color:green" ; pending… DOM Manipulation rewrite style text with preselected element elemPreselected.style.cssText = "color:red" ; elemPreselected.style.cssText = "color:green" ; pending… DOM Manipulation with preselected element elemPreselected.style.color = "red" ; elemPreselected.style.color = "green" ; pending… Add class to DOM with preselected element elemPreselected.className = "red" ; elemPreselected.className = "green" ; pending… DOM Manipulation var elem = document .getElementById( "touched" ); elem.style.color = "red" ; elem.style.color = "green" ; pending… JS CSS Injection addCSSRule( document .styleSheets[ 0 ], "#touched" , "color: red" ); addCSSRule( document .styleSheets[ 0 ], "#touched" , "color: green" ); pending… Add class to DOM var elem = document .getElementById( "touched" ); elem.className = "red" ; elem.className = "green" ; pending…