Monday, May 3, 2010

Unyielding Long Running Loops or Infinite Loops are Not Good For Your Code

There would definitely be cases where there's a need for long running or infinite loops (in some programming terminologies called a noop) somewhere in your applications. Perhaps you need your application to wait for some external processing and thus, simply put in a loop to wait until it gets the expected result or status. Or perhaps simply, you are processing a long list of items within a stack or queue. Whatever the need might be, this area will rapidly eat your memory and CPU resources if you do not yield or release memory allocation every iteration. This is an area in your code that requires careful evaluation, should the need to yield in resources for other processes is required or not, in order for you to come-up with an application with better integrity and performance.

The concept behind this is that, you never let the process iterations stack up, clogging the call stack (which consumes all resources), and provide or yield adequate resources for other processes, both internal and external, to make sure that all necessary operations are working as expected.


Take for example the following code:
while(TRUE) {
//do something
}

Try running the above infinite loop. As it is, without anything to break from or what. This will take your CPU utilization to 100% and load average to very critical levels until it crashes your system. This is how an "unyielding loop" looks like. Most of the similar cases looks a lot like it which uses loops like for, foreach, and do.

The solution to the above code is simple. Simply add a "pause" or a "yield". In this case, I'm gonna use a popular function "sleep" for some *nix OS programming languages. See below.
while(TRUE) {
//do something
sleep(1)
}

Some people might argue that a "1-second" pause is too long for an inexpensive, long running or infinite loop. Maybe it's just a counter or something like that. In that case, you might want to use microsecond pauses instead. Just make sure that you pause just enough time to take first iteration to finish processing and release memory and you should be yielding CPU resources just fine. In PHP, there's a function called "usleep" that does exactly that. There should be equivalents in other programming languages. See below.
while(TRUE) {
//do something
usleep(50) // equivalent to 0.050 seconds
}
  • Related Links Widget for Blogspot

No comments: