字符串是固定长度8,包含字母数字字符,右边用空格填充。
即,
"STRING1 "
"STR2 "
"S "
等。
我在想memcmp
可能是最快的吗?
答案 0 :(得分:10)
如果确保字符串通过特定于编译器的属性在8字节边界上对齐,则可以执行以下操作:
uint64_t a = *((uint64_t *) "STRING1 ");
uint64_t b = *((uint64_t *) "STR2 ");
然后a == b
应该产生一个64位指令。
或者,如果它们只是常量不可变字符串(存储在进程的只读区域中),则可以继续比较const char *
指针本身。它仍然是一个可靠的测试,因为在当前翻译单元中出现两次的字符串文字应该引用相同的内存:
/* fails because the two strings are stored at different locations */
"STRING1 " == "STR2 "
/* should succeed, even the silliest compiler should merge both literals */
"STRING1 " == "STRING1 "
答案 1 :(得分:4)
如果字符串的长度固定相等,则memcmp
是一种很好的方法。