Aggregating Style Changes

JavaScript performance comparison

Test case created by Josh

Info

whether it's faster to change styles all at once (using jQuery) or not

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="myDiv" style="position: absolute; top: 10px, left: 10px; width: 30px; height: 30px;">Hello</div>
<script>
Benchmark.prototype.setup = function() {
    var $myDiv = $('#myDiv');
    var myDiv = $myDiv[0];
    var counter = 1;
    var docFrag = document.createDocumentFragment();
    var div = document.createElement("div");
};
</script>

Preparation code output

Hello

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
aggregate
var c = counter++ % 100;
$myDiv.css({
   top: c + 'px',
   left: c + 'px',
   width: c + 'px',
   height: c + 'px'
});
pending…
no aggregate
var c = counter++ % 100;

myDiv.style.top = c + 'px';
myDiv.style.left = c + 'px';
myDiv.style.width = c + 'px';
myDiv.style.height = c + 'px';
pending…
aggregate with style tag
var c = counter++ % 100;
var style = 'top: ' + c + 'px; ' +
'left: ' + c + 'px;' +
'width: ' + c + 'px;' +
'height: ' + c + 'px;';

myDiv.setAttribute('style', style);
pending…

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

Compare results of other browsers

0 comments

Add a comment