<sarcasm>
Contrary to the other answers, about your statement:
For example, how much optimization will comparing the first character of two strings (and checking if they are equal) before calling strcmp provide?
I think it's an excellent idea. So, we should do this:
int compstr(const char *a, const char *b)
{
if (*a == *b) return strcmp(a+1, b+1);
else return *(unsigned char *)a < *(unsigned char *)b ? -1 : 1;
}
But, why stop there? We should check one more character, giving us better optimization:
int compstr(const char *a, const char *b)
{
size_t i;
for (i=0; *a == *b && i < 2; ++a, ++b, ++i)
if (*a == 0)
return 0;
if (i == 2) return strcmp(a, b);
return *(unsigned char *)a < *(unsigned char *)b ? -1 : 1;
}
Of course, we can do much better than that. Let's make the number of characters to be compared a parameter:
/* Really fast implementation to compare strings,
takes the optimization parameter n_comp */
int compstr(const char *a, const char *b, size_t n_comp)
{
int i;
for (i=0; *a == *b && i < n_comp; ++a, ++b, ++i)
if (*a == 0)
return 0;
if (i == n_comp) return strcmp(a, b);
return *(unsigned char *)a < *(unsigned char *)b ? -1 : 1;
}
But if we are going to all this trouble of comparing the first few characters, why not just do it all by ourselves? So, here's the final, completely optimized version:
/* Final, highly optimized function to compare strings */
int strcmp (const char *a, const char *b)
{
for (; *a == *b; ++a, ++b)
if (*a == 0)
return 0;
return *(unsigned char *)a < *(unsigned char *)b ? -1 : 1;
}
After writing our version, we are happy to find that it is identical to the version in P.J. Plauger's The Standard C Library (and it of course avoids any architecture-specific optimizations that a good library would have used)!
</sarcasm>
In other words, as others have said, there is no point in premature optimization.
Note: I haven't really checked to see if my code snippets above are correct. Another reason to avoid reinventing the wheel: you have to do all the hard work yourself!