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;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 21, 2015 at 4:10
\$\endgroup\$
0

1 Answer 1

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;
 }
answered Mar 21, 2015 at 4:38
\$\endgroup\$
2
  • \$\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\$ Commented Mar 21, 2015 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\$ Commented Mar 21, 2015 at 12:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.