带有任何算术运算符的常量操作数的顺序会影响优化吗?

时间:2019-06-26 05:25:48

标签: c++ assembly optimization c++17 compiler-optimization

假设我们定义了constconstexpr,并且多次执行简单的算术运算符,并且变量和函数调用不会表示或返回常量

>
    #define NU = 3; //Macro or
    const int NU = 3 // general declaration or constexpr
    auto NU = []()constexpr -> int { return 3;}
    int result = 0;

   #Approach one -> const NU on left side of the operator right side could be function call or a function parameter
    for(int i = 0; i< SOME_MAX; ++i) result = NU * foo(); // function call or
    for(int i = 0; i< SOME_MAX; ++i) result = NU * var; // variable

   #Approach two -> const NU on Right side of the operator Left side could be function call or a function parameter
    for(int i = 0; i< SOME_MAX; ++i) result = foo() * NU ;// function call or
    for(int i = 0; i< SOME_MAX; ++i) result = var * NU; // variable

哪种方法会生成优化的汇编->机器代码?

相对于算术运算符而言,常量操作数位于LHS还是RHS上会影响优化性能

注意-在这里我用它来描述我的想法,性能下降或效率低下可以忽略不计,但假设使用一堆常量进行一组复杂的数学运算。

谢谢。

1 个答案:

答案 0 :(得分:6)

应该相同。 最现代的编译器将在编译时评估并传播常量。该理论称为Constant folding或恒定传播。

编辑:在哪方面,都应该有所不同。尽管在定理证明中,我认为像coq一样,证明RHS优化要比LHS优化更困难(或者反之亦然……我忘了。)。