1
\$\begingroup\$

Are there more optimization possible in this code to achieve better performance and minimal memory usage?

#include<stdio.h>
char * strrev(char* str)
{
     int length=0;
     char* str1=str;

     while(*str++)
        ++length;

     str=str1;
     char  temp;

     for ( int i=0; i< length/2; ++i)
     {
           temp= *(str +i);
           *(str +i) = *(str+length -1-i);
           *(str+length -1-i)= temp;
     }

     return str1;
}
int main()
{
    char str[]="Hello World!";
    strrev(str);
    printf("Reversed str:%s", str);

    return 0;

}
\$\endgroup\$
3
\$\begingroup\$

Sure there is... use the native libraries...

Your code here:

 int length=0;
 char* str1=str;

 while(*str++)
    ++length;

counts the number of chars until it finds the null terminator.

This is an inefficient way of doing it, 1 byte at a time. A much more efficient way to do it is to work on word-sized memory chunks - 32-bits and 64-bits on respective platforms. If you do a fold of the 8-bit bytes using bitwise operators on the value, you can identify whether there is a null byte in fewer CPU operations than by processing each byte individually. If this sounds complicated, well, it sort of is, but, on the other hand, it is already done for you:

#include <string.h>

....

    length = strlen(str);

That will likely halve the time needed to find the string length.

Then, your code would be a lot easier to read if you used array-like subscripts to access the chars instead of pointers..... that way you can get rid of the str1 variable as well:

 char  temp;

 for ( int i = 0; i < length/2; ++i) {
       temp = str[i];
       str[i] = str[length - 1 - i];
       str[length - 1 - i] = temp;
 }

If you want, you can reduce that to a while-loop with converging indices:

 int right = length - 1;
 int left = 0;
 while (left < right) {
     temp = str[left];
     str[left++] = str[right];
     str[right--] = temp;
 }
\$\endgroup\$
  • \$\begingroup\$ Doesn't pointer arithmetic faster than array_like subscripts? Or will it be into category of pre-mature optimization and decent compiler will take care it? \$\endgroup\$ – Steephen Mar 21 '15 at 12:10
  • 1
    \$\begingroup\$ @Steephen: You're correct that pointer manipulation is usually faster than array subscripting, however it's worth measuring with your compiler on your computer to be sure. \$\endgroup\$ – Edward Mar 21 '15 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.