Did you know that games with advanced graphics and controls are possible on the Wii’s Internet Channel (Opera 9.x) using nothing but HTML and efficiently-coded Javascript? I’m not talking about Pong, either. I’m referring to games with graphics that rival those of Starfox for the SuperNES or the original Wolfenstein 3D for the PC. This article focuses on thinking in the mindset of optimizing your Javascript code as much as possible for both speed and memory in areas specific to the Wii. Articles already exist on the Wii Remote and the canvas object, so I will not spent a great deal of time on the specifics of those but will dive right into the meat of the topic.
Integer Math
Whenever time-critical calculations must be made, it is a good idea to work in integer-only math. (Plus, pixels are integer coordinates, anyways.) Since javascript variables are all of one type, there is no specific integer variable, so tricks must be employed to pull the extra speed boost from integer calculations over floating-point ones. There are a few ways to do this:
scale = Math.floor((x2-x1)/img.width);
scale = ((x2-x1)/img.width)>>0;
scale = ((x2-x1)/img.width)|0;
For calculations of our needs, always avoid the first example. Javascript’s built-in Math class is very slow compared to bit shifts or bit comparisons. If all values are integers already, then conversions are only needed on divides. For rounding numbers, add half of the denominator to the numerator before dividing. The second example leads us into bit shifting over division and multiplications. Divides (and to a lesser extant: multiplies) can be processor-intensive when used repeatedly, so always use bit-shifts when an integer is going to be multiplied or divided by a power of two, like so:
centerx = (x1+x2)/2; centerx = (x1+x2)>>1;
(more…)