Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;

}
share|improve this question

1 Answer 1

up vote 3 down vote accepted

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;
 }
share|improve this answer
    
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? –  Steephen Mar 21 at 12:10
1  
@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. –  Edward Mar 21 at 12:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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