The less loops the better

July 26th, 2011

If you’ve ever built a game, whether it’s a Flash game, a game for iOS or a game built using HTML5 canvas, you’ll know that the thing that makes the game run is loops. When I built my first Flash game while in school, I just wanted to get the game to work, so I didn’t care how many loops I used but my games were never that complicated, so I don’t think it mattered all that much. But when I started to mess around, building games using HTML5’s canvas, I realized, not matter what anyone says, the browser isn’t as good at running JavaScript and rendering graphics as well as Flash is right now. So, if you want to make good games, you need to optimize your code as much as possible.

Over the last few weeks, I’ve been really optimizing the vertical space shooter game that I built for the tutorial I did. One thing I realized as I was working on it, was that I should be using only as many loops as I need to run the code. Right around the time I was figuring this out, I watch a video of a presentation done by Mozilla Evangelist Rob Hawkes where he said the exact same thing, that you need to be careful about how many loops you have running in your game.

Whats the big deal about having too many loops? Well, think about it this way. If you have five loops in your game and you’re running it at something like 30 frames a second, you need to run all five loops thirty times each second. Think about a situation where you have a for loop inside another for loop. This is a pretty common situation and, let’s say the outer loop runs six times and the inner loop runs 9 times, now you’re going to run that interior for loop 1620 times a second. If it’s doing any kind of hard work, that’s going to slow things down.

One of the things we as developers need to remember is that, if you’re like me, you’ve got a quad core processor and you’re probably using a browser like Mozilla’s Aurora or Google Dev version, so you’re code is going to be a lot faster. I bet most of the people out there aren’t going to be running a crazy fast browser on a crazy fast machine. So, and I’m sure you’ve heard this before, but optimizing your code is always a good idea, which is surprising how many developers out there don’t do it.

The moral of the story is this: use as few loops are you need so your code runs faster. I’m sure for experienced programmers this seems like common sense, but I think it’s a good thing to bring up for beginners.

Leave a Reply

Your email address will not be published. Required fields are marked *