Home > code optimization > Alternating Algorithms

Alternating Algorithms

I picked this tip up a while back while reading a book about code quality. This was a trick back in the C days.


Typically alternating logic goes something like this:
int x = 0;
while ( x < rownum ) {
  if ( x % 2 == 0 ) {
    row.color = ‘blue’;
  } else {
    row.color = ‘red’;
  }
  x++;
}

That works, but your doing a modulus function and an addition just to toggle between values.

Instead I use this:
int x = 0;
string[] colors = {‘blue’,’red’};
foreach( row in table )
{
  row.color = colors[x];
  x = 1 – x;
}

The x = 1 – x; will always toggle between 1 and 0, as long as no value other than 1 or 0 is assigned to it. Now you’re just looking at an extra array allocation (you may already have one defined anyway) and a subtraction operation. You also lose the if/else block. Everything’s in one loop block.

This was needed more in the days where cycles were rare and doing everything in as few opps mattered. Not so much today, but I think it is also cleaner code.
Categories: code optimization Tags:
  1. No comments yet.
  1. No trackbacks yet.

%d bloggers like this: