Sunday, October 18, 2009

Code can be both clean and efficient

Chapter 26 of Code Complete focuses on code tuning - the art of modifying code to improve performance. One example given is a switched loop:

  for (i = 0; i < count; i++)
  {
      if (sumType == SUMTYPE_NET)
      {
          netSum = netSum + amount[i];
      }
      else
      {
          grossSum = grossSum + amount[i];
      }
  }

Notice the 'if' statement inside the loop. If the array is rather large, this statement will be evaluate numerous times, despite the fact that the result will never change. The recommended solution is to unswitch the loop, so the 'if' statement is only evaluated once:

  if (sumType == SUMTYPE_NET)
  {
      for (i = 0; i < count; i++)
      {
          netSum = netSum + amount[i];
      }
  }
  else
  {
      for (i = 0; i < count; i++)
      {
          grossSum = grossSum + amount[i];
      }
  }

This recommendation was given with one warning: this code is harder to maintain. If the logic for the loops needs to change, you have to make sure to change both loops to match.

As with most coding tasks, there is more than one possible solution. In this case the ideal approach is to have both a single comparison and a single loop. If we throw one additional variable into the code, we can calculate the summation and then add it accordingly:

  for (i = 0; i < count; i++)
  {
      arraySum = arraySum + amount[i];
  }
 
  if (sumType == SUMTYPE_NET)
  {
      netSum = netSum + arraySum;
  }
  else
  {
      grossSum = grossSum + arraySum;
  }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.