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.