Does the order of the constant operand with any arithmetic operator affect optimization?

Viewed 110

Assume we define const or constexpr and we do simple arithmetic operator, several times, also variables and function calls won't express or return constants.

    #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

Which approach will generate optimized assembly -> machine code?

Whether constant operand to be on LHS or RHS respect to the arithmetic operator will affect the optimization or performance?

Note - Here I used it for picture the idea I have , the performance hit or in-efficiency could be negligible but, assume set of complex mathematical operations using bunch of constants.

Thanks.

1 Answers

It should be the same. Most Modern compilers will evaluate and propagate constants at compile time. The theory is called Constant folding or Constant Propagation.

EDIT: In terms of which side, it should not be a different. Although, I think in theorem provers, like coq, it is more difficult to prove RHS optimisations then LHS optimisations (or maybe the other way around... I forgot.).

Related