I didn't bother optimizing Buzz Grid initially, as even on my elderly machine it appeared to work just fine. But after playing the game some more, I noticed that on a high load it tended to stutter and respond slowly to keys, especially on level 4 (not sure why, since level 3 has an equally complex map, and level 5 has considerably more traps and prizes). So I figured digging into the code a bit couldn't hurt. Luckily, Arora — my favorite WebKit browser — comes with an equivalent of Firebug built-in, including a profiler. Here's what it told me:
- As I suspected, the most time by far is spent in the rendering engine. I did go for the low-hanging-fruit optimizations in other parts of the game — most notably
WorldModel.update()
— but it's barely noticeable. - That said, the inherent slowness of object property lookup in JS did make an appearance even in the renderer. Piece of advice: wherever you see something like
this.property
appearing repeatedly in a method, do a var prop = this.property;
early and use the local variable instead. In many cases, this will also make your code shorter and clearer. fillText()
is slow. That's not exactly a surprise, nor is there much I can do about it. I generously applied the previous optimization to Renderer.renderHUD()
and that was it.- Similarly,
stroke()
appears to be slow, but that's probably because of how much work it does in Renderer.strokeGrid()
. The only thing to optimize in that particular function would be not drawing the grid segments that lie outside the viewport. I suspect the checks would take longer than the actual drawing operations, though, not to mention the damage to code clarity. - Calls to
fillRect()
and fill()
also take up a lot of time, due to them being called very often. But while I can't help with the former, it turns out I was being too conservative with regard to what shapes can be combined in a single path.
Overall, the profile report didn't change much after all this; it does look like I won as much as 7-10% overall, which unfortunately is not enough to fix the original issue completely. I'll have to settle for a noticeable difference instead. Rendering still uses up most of the time, followed by WorldModel.handleCollisions();
the single most called function is Mob.within()
. Speaking of collision handling, I finally found (and fixed) a long standing bug which sometimes made roamers vanish into thin air, not that anyone missed them. That also improved performance by a few percent, incidentally.
All in all, optimizing Buzz Grid was worth it. I didn't accomplish my main goal but the experience gained will come in handy one day.