The first draft of Glow Flow is up and running, but response speed is sluggish. It can be argued this is an upside: it adds the illusion my glowing rainbow liquid is viscous, taking a bit of time to flow. But I want to see if faster responsiveness would feel better, so I start hunting for room for improvement. Here is a summary of top gains:
Only recalculate values when they change
The first draft were recalculating my rotation matrices for every LED. However, the accelerometer based rotation matrix values only change once per frame, so I could do it in
beforeRender() once per frame instead of doing that work in
render3D() 300 times per frame (once per LED.) That is 299 times too many! Fixing this mistake had a tremendous impact. Thanks to Ben for pointing this one out.
Skip multiplication with zero or one
A 3D transform matrix is a general mechanism to handle every possible 3D operation. Calculating a transform involves multiplying sixteen numbers. However, Glow Flow only requires two 3D operations: rotate about the Y axis and rotate about Z axis. The transform matrix for these operations are mostly filled with zeroes. We don’t need to perform a multiplication operation when we already know the result is going to be zero. These multiplications also have elements filled with one, which we can replace with an assignment operation. This cuts down from sixteen multiplications down to four. The improvement here is almost fourfold, corresponding to the ratio of reduction in multiplication.
Minimize data movements
Avoid using global variables is good programming practice, but when trying to extract every bit of performance, it is sometimes worthwhile to put that option back in the toolbox. In the case of Glow Flow Pixelblaze program, many things that are commonly passed as parameters are instead stored as globals. Example: the two rotate transform matrices, as well as the coordinate being transformed. The improvement here is very small, only a few frames per second, but noticeable.
These changes improved frame rate and responsiveness, making it more dynamic and giving me breathing room to add more features to Glow Flow.
Pixelblaze pattern code for Glow Flow is available on Github.