我听到很多人说
int a = 0;
a += 10;
比
int a = 0;
a = a + 10;
这是为什么?我用 gdb 调试了它,它是完全一样的指令。
数据库:
第一的
(gdb) list
1 int main()
2 {
3 int counter = 0;
4 counter = counter + 10;
5 return 0;
6 }
(gdb) disassemble main
Dump of assembler code for function main:
0x00000000004004cc <+0>: push %rbp
0x00000000004004cd <+1>: mov %rsp,%rbp
0x00000000004004d0 <+4>: movl $0x0,-0x4(%rbp)
0x00000000004004d7 <+11>: addl $0xa,-0x4(%rbp)
=> 0x00000000004004db <+15>: mov $0x0,%eax
0x00000000004004e0 <+20>: pop %rbp
0x00000000004004e1 <+21>: retq
End of assembler dump.
第二
(gdb) list
1 int main()
2 {
3 int counter = 0;
4 counter += 10;
5 return 0;
6 }
(gdb) disassemble main
Dump of assembler code for function main:
0x00000000004004cc <+0>: push %rbp
0x00000000004004cd <+1>: mov %rsp,%rbp
0x00000000004004d0 <+4>: movl $0x0,-0x4(%rbp)
0x00000000004004d7 <+11>: addl $0xa,-0x4(%rbp)
=> 0x00000000004004db <+15>: mov $0x0,%eax
0x00000000004004e0 <+20>: pop %rbp
0x00000000004004e1 <+21>: retq
End of assembler dump.
那么为什么 "(variable) += (value)" 比 "(variable) = (variable) + (value)" 快呢?