Skip to content

Instantly share code, notes, and snippets.

@mgronhol
Last active April 6, 2024 14:48
Show Gist options
  • Save mgronhol/018e17c118ccf2144744 to your computer and use it in GitHub Desktop.
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;
}
Copy link

ghost commented Sep 3, 2016

looked at this... it came out to be 11s vs. 7s for strncmp on my mac for some large number of comparisons... :\

@nmmmnu
Copy link

nmmmnu commented Jul 12, 2017

I got similar results for this and strncmp

@MarkReedZ
Copy link

MarkReedZ commented Mar 31, 2018

https://github.com/natsys/blog has a test and benchmark. Just clone, cd fast_str, make.

@waddlesplash
Copy link

What's the license on this?

@JL2210
Copy link

JL2210 commented Aug 22, 2019

@mgronhol What's the license?

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