Typically when manipulating display objects in Flash, applying positional data is a trivial task so you wouldn’t think twice about applying the data on every game loop. It doesn’t matter that the object hasn’t moved on that frame. The overhead would be minimal, you can just reapply without penalty – in fact to engage with any conditional to test for the need to apply could be more costly in the long run.
With DOM manipulation, any update seems to be fairly processor expensive. Very non-trivial. Here it is essential that updates should be applied ONLY when absolutely necessary.
I ran a test script at JSPerf.com which demonstrated the issue. I set up a Div with some simple text content. Then manipulate it on every iteration. I move the x-position by 0.2, then round off the position before applying. To optimise I only apply the dom manipulation when the actual object has changed position. The results are stark. A massive performance boost.
The code used is simple, and as follows. Create a div, populate then manipulate:
var targetDIV = document.createElement(“div”);
targetDIV.innerHTML = “test data”;
document.doby.appendChild(targetDIV);
var posX =0, prevPosX=0;function unoptimisedManipulation()
{
posX+=0.2;
var roundX = Math.round(posX);if(posX>500) {posX=0;}
targetDIV.style.left=roundX+”px”;prevPosX = roundX;
}function optimisedManipulation()
{
posX+=0.2;
var roundX = Math.round(posX);
if(prevPosX!=roundX)
{
if(posX>500) {posX=0;}
targetDIV.style.left=roundX+”px”;prevPosX = roundX;
}
}
The results aren’t indicating that DOM manipulation should be avoided – Android devices really struggle with Canvas so DOM is preferable – it just takes a bit of effort to make the DOM production ready.
Try running the tests yourself at JSPerf.com : http://jsperf.com/optimising-dom-access
0 Responses to “HTML5 Game Dev. DOM Manipulation. It’s costly, so minimise its use.”