C optimization

One common thing that I run into when trying to optimize C code is when looping through a string. Here’s the slow way:

int i;
for (i = 0; i < strlen(str); i++)
   str[i] ^= c;

This can be really slow since we’re calling strlen before each iteration. So a simple way to make it faster is to change it like this:

int i, len = strlen(str);
for (i = 0; i < len; i++)
   str[i] ^= c;

Yet then again, we can still optimize this further:

int i; len = strlen(str) - 1;
for (;i--;) str[i] ^= c;

With that code, we are looping through the string backwards from the last character. And i– both decrements i and acts as a test condition to see if i is greater than 0.

This next optimization is powerful but not guaranteed. Using the [b]register[/b] keyword in C/C++ will make a request to the compiler to store the following variable in a register instead of in memory. As you should know, the speed of reading data from registers is faster than reading from memory which is faster than reading from a hard disk. For x86 32-bit computers there are only 5 registers I can think that can be used to store a requested variable.

register int i;
register char* str;
register float f;

And of course, have early loop breaking. Compare the following that searches for the first specified char in a string:

int firstof(char* str, char ch) {
   int i, len = strlen(str);
   bool found = false;
   for (i = 0; i < len; i++) {
      if (str[i] == ch) found = true;
   }
   return found;
}
int firstof(char* str, char ch) {
   int i, len = strlen(str);
   for (i = 0; i < len; i++) {
      if (str[i] == ch) return 1;
   }
   return 0;
}

With the early loop break in the second one, it will not continue to loop after it has been found.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: