指针移动与数组下标移动效率问题。
看书我硬是没看懂。。。 指针 运行效率
[解决办法]
下面下标的访问效率 要高很多 很多!
下标是直接访问,指针是间接访问
[解决办法]
这书已经过时了。现在cpu的优化指令下,下标访问更快已经是很正常的了。
[解决办法]
这个要测试过才知道
[解决办法]
x86_64位centos,gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)汇编结果
1 #include <stdio.h>
2 int main()
3 {
4 int a[5], i, *p;
5 for(i = 0; i < 5; ++i)
6 a[i] = 0;
7
8 for(i = 0; i < 5; ++i)
9 *(a + i) = 0;
10
11 for(p = a; p < a + 5; ++p)
12 *p = 0;
13 return 0;
14 }
~
movl $0, -12(%rbp)
14 jmp .L2
15 .L3:
16 movl -12(%rbp), %eax
17 cltq
18 movl $0, -32(%rbp,%rax,4)//1条
19 addl $1, -12(%rbp)
20 .L2:
21 cmpl $4, -12(%rbp)
22 jle .L3
23 movl $0, -12(%rbp)
24 jmp .L4
25 .L5:
26 movl -12(%rbp), %eax
27 cltq
28 leaq 0(,%rax,4), %rdx//4条
29 leaq -32(%rbp), %rax
30 addq %rdx, %rax
31 movl $0, (%rax)
32 addl $1, -12(%rbp)
33 .L4:
34 cmpl $4, -12(%rbp)
35 jle .L5
36 leaq -32(%rbp), %rax
37 movq %rax, -8(%rbp)//p = a;
38 jmp .L6
39 .L7:
40 movq -8(%rbp), %rax
41 movl $0, (%rax)//*p=0
42 addq $4, -8(%rbp)//++p
43 .L6:
44 leaq -32(%rbp), %rax
45 addq $20, %rax
46 cmpq -8(%rbp), %rax
47 ja .L7
48 movl $0, %eax
49 leave