Performance tips and tricks – part 1

In this post series I will take a look at the different tips and tricks that can increase the performance of your application. You probably already know some of them and some of them are even just a bit of logical thinking. In any case, it should help you remember the different techniques. I took all these tips and tricks out of my article High Performance Game Development (The revised version – coming out soon) since they apply to almost all languages.

Move work out of loops

This one is kind of obvious, but it can be hard to identify in some cases. You simply move work from inner loops to outer loops or even out of a loop altogether. I’ve made some simple examples of this:

Before:

MoveOutOfLoop

After:

MoveOutOfLoop-optimized

Don’t use loops

This is much like the previous one. One important difference is that you don’t use loops at all. You will save a lot of instructions and thus you will have better performance.

Before:

DontUseLoops

After:

DontUseLoops-optimized

Use constants whenever possible

Using constants can greatly improve performance. The compiler can make better decisions about your code and make use of low level optimizations that speed up the execution of the code.

Before:

Constants

After:

Constants-optimized

Note how we can use the const keyword on the addition variable. This is only possible when the depending variables are also marked with the const keyword.

Simplify variables

Whenever you can, make sure to simplify variables to removing redundant operations. This might not always be possible and sometimes it can severely decrease the code readability. In this specific case you can maintain the readability by simply using the const keyword. The compiler will then simplify the variables for you.

Before:

SimplifyVariables

After:

SimplifyVariables-optimized

Comments

Altough the Simplify variables might make your code a tiny bit faster, you do create magic numbers which really is a bad coding practice (altough we all do it from time to time.

However you can combine the 'Simplify variables' and the 'Use constants whenever possible' tips to get:

const int offsetY = 20;
cont int offsetX = 50;
const int centerX = 300;
const int centerY = 300;

Vector2 center = new Vector2(centerX + offsetX, centerY + offsetY);

Or maybe even combine (centerX + offsetX) in a new constant variable. (Same for the Ys).

A second option might be to document the magic numbers in a comment line right above their use.

(PS. isnt there a blogspot code markup tool? I appreciate the effort the create pictures from all your code samples, but this makes it hard to use them).

Anyway, good simple post! We so often forget these simple tricks.

Popular posts from this blog

.NET Compression Libraries Benchmark

The Ramer-Douglas-Peucker Polygon Simplification Algorithm

The Power of Wolfram Alpha - Now in a .NET API