Last active
April 6, 2024 14:48
-
-
Save mgronhol/018e17c118ccf2144744 to your computer and use it in GitHub Desktop.
Fast string compare
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
I got similar results for this and strncmp
https://github.com/natsys/blog has a test and benchmark. Just clone, cd fast_str, make.
What's the license on this?
@mgronhol What's the license?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
looked at this... it came out to be 11s vs. 7s for strncmp on my mac for some large number of comparisons... :\