Feb 2, 2021
為什麼 memcmp 會比 for loop check 快?
之前在實作這篇時,一開始是用以下方式實作:
while (fgets(in_str, FGETS_SIZE, in_f) != NULL) {
for (int i = 0; i < strlen(in_str); i++) {
if (in_str[i] == '"') {
has_quote = has_quote ? false : true;
} else if (has_quote &&
(in_str[i] == '\n' || in_str[i] == '\r' ||
in_str[i] == '\t')) {
in_str[i] = ' ';
}
} fprintf(out_f, "%s", in_str);
}
但是發現並沒有比 gawk 快多少,後來改用 strstr
速度整個起飛,去查看 strstr 的 source code 發現其實也只是 call memcmp
而已,然後這篇文章中有給回答:
memcmp
is often implemented in assembly to take advantage of a number of architecture-specific features, which can make it much faster than a simple loop in C.
原來是組語的部分,恩,跟我想的一樣呢
大概是這樣