#include <stdio.h> void test() { char *str = "String"; // (1) // char str[] = "String"; // (2) // Segmentation Fault occurs when using (1) // but does not occur when using (2) str[0] = 's'; printf("%s\n", str); } int main() { int i; for (i = 0; i < 10000000; i++) { test(); } return 0; }
アセンブラの diff 取ると
> diff a.s b.s 12,15c12,19 < movl $.LC0, -4(%ebp) < movl -4(%ebp), %eax < movb $115, (%eax) < movl -4(%ebp), %eax --- > movl .LC0, %eax > movl %eax, -7(%ebp) > movzwl .LC0+4, %eax > movw %ax, -3(%ebp) > movzbl .LC0+6, %eax > movb %al, -1(%ebp) > movb $115, -7(%ebp) > leal -7(%ebp), %eax
最初は速度差あったみたいなんだけど、キャッシュに乗った後はあんまり速度変わらなかった。