为了磨练我的 C 技能,我下载了 eglibc 源代码并遇到了 strncpy。我不明白他为什么区分 n
int
STRNCMP (const char *s1, const char *s2, size_t n)
{
unsigned char c1 = '\0';
unsigned char c2 = '\0';
if (n >= 4)
{
size_t n4 = n >> 2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
} while (--n4 > 0);
n &= 3;
}
while (n > 0)
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
n--;
}
return c1 - c2;
}
可能与我不知道的内存布局有关,请赐教。
最佳答案
这是一个 unrolled loop 。以让二进制文件更大一点为代价,它通过为每 4 个要比较的字节消除 3 个递减、3 个分支和 3 个条件来加速字符串比较。
通过使用与 Duff's device 相同的技术,优化甚至可以更进一步,尽管不清楚这实际上会更快。从链接页面,
关于c - strncmp的实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37034869/