Tag Archive for Professional Code

Optimizing For Loops

I am pretty obsessed with getting every little bit of performance I can out of my code, especially when developing for mobile platforms. For loops, believe it or not, can be optimized using some very simple tricks. Normally you probably write a for loop like this:

for (int i = 0; i < some.Length; i++) {
    // Code
}

If you know that the length of whatever you're iterating is going to be less than 256 (0-255) you can use byte instead of int, if you aren't completely certain, you can probably get away with ushort (0-65,535). This will free up 24 and 16 bits as compared to int respectively, it's not much, but it can add up. You can also pre-lock the length into a variable to help speed things up. The reason this works is because for loop check their condition (second block) every single iteration. This means that you are accessing the length property every single iteration. Accessing a member of a class is more expensive than accessing a single variable, and thus adds up over many iterations. The performance change might be slight, but it adds up pretty quickly, especially if you are iterating through hundreds of pieces of data every single frame. So, what should the for loop look like? Well, like this:

byte length = some.Length;
for (byte i = 0; i < length; i++) {
    // Code
}

The Importance of Class and Object Oriented Programming

While class is certainly important to have in real life, it is equally important to have while programming. Taking advantage of an Object Oriented Programming method (or OOP method) may very well be one of the most important higher concepts to learn and understand. This article helps cover what OOP is, its benefits, and how to use it.

Read more

Finite State Machines

To expand on my earlier post about enumerations I'm going to look at Finite State Machines in a relatively general sense. Let's start with breaking down what exactly a Finite State Machine is. We can look at the descriptive words to see that it is a machine, or system, that consists of a finite number of states. Great, but what does that mean? In a sense it is a way to package your code so only the desired pieces run at the desired time, this makes them very useful for succinct organization. In the rest of the article we'll look at different ways to implement the system, as well as the pros and cons of each.

Read more