The gold standard of optimization: A look under the hood of RollerCoaster Tycoon
RollerCoaster Tycoon, a classic game from 1999 is still worth dissecting for its performance to this day. First a quick primer on bit shifting (new to me—I’m used to high level languages!):
What the
<<operator does here [NewValue = OldValue << 2] is called bit shifting, meaning all the bits that store the value of the variable are shifted to the left, in this case by two positions, with the new digits being filled in with zeros. Since the number is stored in a binary system, every shift to the left means the number is doubled.
Since this is a lot faster than multiplication, Chris Sawyer decided to exploit this as much as possible:
The even more interesting point about those calculations, however, is how often the code is able to do this. Obviously, bit shifting can only be done for multiplications and divisions involving a power of two, like 2, 4, 8, 16, etc. The fact that it is done that often indicates that the in-game formulas were specifically designed to stick to those numbers wherever possible, which in most modern development workflows is basically an impossibility.
I do want to disagree with that last bit. Impossibility sounds too harsh. We can’t decide the requirements for stakeholders, but plenty of things aren’t as set in stone as they seem. It’s our job to nudge things in the right direction, so the result works with the grain of our programs.