Last active
June 6, 2017 20:55
-
-
Save ungive/c6dc211f78a8d87e7552dd15c3c16043 to your computer and use it in GitHub Desktop.
Optimised string comparison.
This file contains hidden or 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
#include <stddef.h> | |
#include <stdint.h> | |
int strncmp_fast(const char *str1, const char *str2, size_t size) | |
{ | |
typedef uint_fast32_t word_t; | |
int blocks = size >> 2; | |
if (size > sizeof(word_t)) { | |
word_t *word1 = (word_t *)str1; | |
word_t *word2 = (word_t *)str2; | |
for (int block = 0; block < blocks; ++block) { | |
if (!(word1[block] ^ word2[block])) | |
continue; | |
int i = block << 2; | |
const char *a = str1 + i, *b = str2 + i; | |
if ((a[0] ^ b[0]) || !a[0]) return a[0] - b[0]; | |
if ((a[1] ^ b[1]) || !a[1]) return a[1] - b[1]; | |
if ((a[2] ^ b[2]) || !a[2]) return a[2] - b[2]; | |
if ((a[3] ^ b[3]) || !a[3]) return a[3] - b[3]; | |
} | |
} | |
int offset = blocks << 2; | |
if (offset < size) { | |
const char *a = str1 + offset, *b = str2 + offset; | |
if ((a[0] ^ b[0])) | |
return a[0] - b[0]; | |
if (offset < size - 1) { | |
if ((a[1] ^ b[1])) | |
return a[1] - b[1]; | |
if (offset < size - 2 && (a[2] ^ b[2])) | |
return a[2] - b[2]; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment