当启用优化编译时,编译器会以任何方式生成相同的代码,您应该使用任何样式使代码对您和维护代码的人更易读。
例如
#include <cstddef>
#include <vector>
struct unitStruct {
int field1;
int field2;
int field3;
};
void noref(std::vector<unitStruct> & units, size_t unitIndex, int value1, int value2, int value3)
{
units[unitIndex].field1 = value1;
units[unitIndex].field2 = value2;
units[unitIndex].field3 = value3;
}
void ref(std::vector<unitStruct> & units, size_t unitIndex, int value1, int value2, int value3)
{
unitStruct& unit = units[unitIndex];
unit.field1 = value1;
unit.field2 = value2;
unit.field3 = value3;
}
用gcc编译和优化启用-O3
g++ -O3 -c struct.cpp -o struct.o
objdump -D struct.o|less
生成相同的代码 - 前三个指令出现在不同的顺序,但仅此而已:
0000000000000000 <_Z5norefRSt6vectorI10unitStructSaIS0_EEmiii>:
0: 48 8d 04 76 lea (%rsi,%rsi,2),%rax
4: 48 8b 37 mov (%rdi),%rsi
7: 48 8d 04 86 lea (%rsi,%rax,4),%rax
b: 89 10 mov %edx,(%rax)
d: 89 48 04 mov %ecx,0x4(%rax)
10: 44 89 40 08 mov %r8d,0x8(%rax)
14: c3 retq
0000000000000020 <_Z3refRSt6vectorI10unitStructSaIS0_EEmiii>:
20: 4c 8b 0f mov (%rdi),%r9
23: 48 8d 04 76 lea (%rsi,%rsi,2),%rax
27: 49 8d 04 81 lea (%r9,%rax,4),%rax
2b: 89 10 mov %edx,(%rax)
2d: 89 48 04 mov %ecx,0x4(%rax)
30: 44 89 40 08 mov %r8d,0x8(%rax)
34: c3 retq
您应该注意在-O3中启用了优化。 –
@RobK好点,我会强调这一点,谢谢。 – amdn