Skip to content

Instantly share code, notes, and snippets.

@mgronhol
Last active July 15, 2025 12:17
Show Gist options
  • Select an option

  • Save mgronhol/018e17c118ccf2144744 to your computer and use it in GitHub Desktop.

Select an option

Save mgronhol/018e17c118ccf2144744 to your computer and use it in GitHub Desktop.
Fast string compare
int fast_compare( const char *ptr0, const char *ptr1, int len ){
int fast = len/sizeof(size_t) + 1;
int offset = (fast-1)*sizeof(size_t);
int current_block = 0;
if( len <= sizeof(size_t)){ fast = 0; }
size_t *lptr0 = (size_t*)ptr0;
size_t *lptr1 = (size_t*)ptr1;
while( current_block < fast ){
if( (lptr0[current_block] ^ lptr1[current_block] )){
int pos;
for(pos = current_block*sizeof(size_t); pos < len ; ++pos ){
if( (ptr0[pos] ^ ptr1[pos]) || (ptr0[pos] == 0) || (ptr1[pos] == 0) ){
return (int)((unsigned char)ptr0[pos] - (unsigned char)ptr1[pos]);
}
}
}
++current_block;
}
while( len > offset ){
if( (ptr0[offset] ^ ptr1[offset] )){
return (int)((unsigned char)ptr0[offset] - (unsigned char)ptr1[offset]);
}
++offset;
}
return 0;
}
@vegasword
Copy link

Why is there a condition if( len <= sizeof(size_t) ){ fast = 0; } ? This introduced a bug where I couldn't compare a string of length 8... I removed it and it worked as I expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment