I’m enjoying myself with some optimizing today (yeah I’m weird like that). So I thought I’d jot down some of my tips for making your game faster. These are general, not language-specific tips.
Never run code you don’t have to run
Seems obvious but few people actually do this. For example, in democracy 3, the simulation calculates the popularity of each policy by asking every voter if they benefit from it. That question is complex, and there are a few hundred policies and 2,000 voters. This takes time. Solution: I only ask them about a policy if I need the answer right now. Some policies can go a dozen turns without the player ever checking their popularity, so why keep calculating it?
If you have a dozen icons that are always drawn one after another on the same screen, stick them in a texture atlas. If you are 100% they will never overlap, then draw them in a single draw call. the less texture swaps and draw calls, the faster your code. This is trivial to do in 3D, an absolute nightmare to do properly in 2D, but it’s worth it.
If you have a variable that is complex to evaluate, evaluate it once, then cache it until it changes (we tend to call that setting it ‘dirty’). If there is some data that is going to be accessed a LOT, then make a local copy of it. And if you have a lot of stuff to write to disk, to the same file, buffer it. Writing to or reading from a file is slow, especially if you are going to do it a lot. Reading in a single file is much quicker than opening 200 of them one after another.
Don’t use sqrt()
Do you ever use sqrt()? never realised how scarily slow it was? Most of the time you can keep the squared result and use some clever tricks to not actually need the sqrt() result. If you were going to get the sqrt() and compare it against a value, just multiply the comparison value by itself and check it that way instead. it’s amazingly faster.
Use the right container class
Sometimes you will use a list where a vector will do. The vector is MUCH faster. And you know what is faster still. I mean REALLY fast? An array. If you really need speed, and the array size won’t change that often, allocating an array of items is much faster and is worth the overhead.
If you have a collection of objects that keep getting created and destroyed, you want to wrap that up. Stick a factory object around them to handle their construction and destruction. That way, you can just set them inactive on destruction, and save yourself the hassle of the creation and destruction when it comes time to re-use them. Setting a single flag to say an object is ‘dead’ is way faster than calling a destructor, and resetting is way faster than a constructor.
Obviously there are lots more tips, and you should get a decent commercial profiler. That PC you develop on is a super-computing beast. if your game takes more than a few seconds to load, you are being sloppy.