Skip to content

Instantly share code, notes, and snippets.

@larytet
Last active August 26, 2017 08:56
Show Gist options
  • Save larytet/7faab870e05d382c7afe3f6225da3d98 to your computer and use it in GitHub Desktop.
Save larytet/7faab870e05d382c7afe3f6225da3d98 to your computer and use it in GitHub Desktop.
An implementation of strcmp()
// https://godbolt.org/g/56Lv4f - 62 opcodes
int strcmp_original(char *a, char *b)
{
int c = strlen(a) > strlen(b) ? strlen(a) : strlen(b);
char * d;
for (d = a;d < a + c;++d, ++b)
{
if (*d != *b)
{
return (*d - *b);
}
}
return 0;
}
// 56 opcodes (39 lines with -O2)
int strcmp_better(char *a, char *b)
{
int len_a = strlen(a);
int len_b = strlen(b);
int len_max = len_a > len_b ? len_a : len_b;
char *p;
for (p = a;p < (a + len_max);++p, ++b)
{
if (*p != *b)
{
return (*p - *b);
}
}
return 0;
}
// 30 opcodes (19 lines with -O2)
int strcmp_refactored(const char *s1, const char *s2)
{
while ((*s1 != 0) && (*s1 == *s2))
{
++s1;
++s2;
}
return (*s1 - *s2);
}
// 15 opcodes with -O2
int strcmp_refactored_2(const char *s1, const char *s2)
{
while (1)
{
int res = ((*s1 == 0) || (*s1 != *s2));
if (__builtin_expect((res),0))
{
break;
}
++s1;
++s2;
}
return (*s1 - *s2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment