1

I like to use const& type T = LongVariableName to relabel variables in a short segment of code, especially one that involves formulas.

For example:

const double& x = VectorNorm;
double y = a*x*x*x + b*x*x + c*x + d;

I figure the compiler should be smart enough to optimize these reference variables away. Will that almost always happen? When won't it?

4

1 回答 1

0

这取决于编译器和您设置的优化选项 - 不能保证它会或不会被优化掉。启用优化的现代编译器可能会将其优化掉,但更好的问题是:您应该关心吗?除非您处于每秒运行数千次的紧密循环中,否则不要担心。代码清晰通常比减少几个时钟周期更重要。

但无论如何,让我们来看看。我正在通过 MinGW 使用 gcc 4.7.2。我们将使用以下代码:

所以.cpp:

#include <cstdio>

int main()
{
    float aReallyLongNameForAVariable = 4.2;
#ifdef SHORT_REF
    const float& x = aReallyLongNameForAVariable;
    float bar = x * x * x;
#else
    float bar = aReallyLongNameForAVariable * aReallyLongNameForAVariable * aReallyLongNameForAVariable;
#endif
    printf("bar is %f\n", bar);
    return 0;
}

没有“速记参考”,我们得到以下程序集:

g++ -S -masm=intel -o noref.S so.cpp

call    ___main
mov eax, DWORD PTR LC0
mov DWORD PTR [esp+28], eax
fld DWORD PTR [esp+28]
fmul    DWORD PTR [esp+28]
fmul    DWORD PTR [esp+28]
fstp    DWORD PTR [esp+24]
fld DWORD PTR [esp+24]
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
mov eax, 0
leave

现在让我们使用参考:

g++ -DSHORT_REF -S -masm=intel -o ref.S so.cpp

call    ___main
mov eax, DWORD PTR LC0
mov DWORD PTR [esp+20], eax
lea eax, [esp+20]
mov DWORD PTR [esp+28], eax
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
fmulp   st(1), st
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
fmulp   st(1), st
fstp    DWORD PTR [esp+24]
fld DWORD PTR [esp+24]
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
mov eax, 0
leave

所以它是一个多一点的组装。但是当我们开启优化时会发生什么?

g++ -DSHORT_REF -O2 -S -masm=intel -o ref.S so.cpp
g++ -O2 -S -masm=intel -o noref.S so.cpp

两者都生成相同的程序集:

call    ___main
fld DWORD PTR LC0
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
xor eax, eax
leave

所以你有它。现代编译器(至少 gcc)优化了引用。

于 2013-01-18T21:11:31.233 回答