Optimising DOM Access

JavaScript performance comparison

Test case created by Jon Howard

Info

DOM manipulation seems expensive.

This is to see how much processor usage can be saved by only touching the DOM when needed.

Preparation code

<div id="TargetDIV">Test DIV</div>
<script>
Benchmark.prototype.setup = function() {
    var targetDIV = document.getElementById("TargetDIV");
    var posX =0, prevPosX=0;
};
</script>

Preparation code output

Test DIV

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Un-optimised. Move on every iteration.
posX+=0.2;
var roundX = Math.round(posX);

if(posX>500)posX=0;
targetDIV.style.left=roundX+"px";

prevPosX = roundX;
pending…
Optimised. Only move when necessary
posX+=0.2;
var roundX = Math.round(posX);
if(prevPosX!=roundX)
{
   if(posX>500)posX=0;
   targetDIV.style.left=roundX+"px";

   prevPosX = roundX;
}
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