Should I avoid operations between constants in a loop?

6

In C ++ is there any sort of optimization or caching that prevents the same mathematical operation between constants from being repeated, especially in loops , thus decreasing application performance?

For example:

for (int i=0; i<=100; i++)
    std::cout << i  << " metros/s:" << " = " << i * (3600 / 1000) << " Km/h" << endl;

The above example is obviously fictional, but it is just to illustrate the situation. It could be a loop of millions of times with hundreds of calculations involving repeated constants.

Then I ask:

  • Will the "(3600/1000)" calculation run repeatedly over 100 times of loop ?
  • In order to avoid performance loss, should I store this calculation in a constant variable before loop and change the calculation by this variable?
  • Or do not I have to worry about this because C ++ gives a way to optimize these situations automatically to avoid performance loss?
  • I understand that this question is pertinent, because it involves the programming style that should be adopted.

        
    asked by anonymous 23.04.2018 / 00:56

    1 answer

    6
      

    Will the "(3600/1000)" calculation run repeatedly over the 100 times of the loop?

    There is no guarantee that it will occur, but in practice it will be optimized yes and the operation will be resolved at compile time, not costing execution.

      

    So, in order to avoid performance loss, should I store this calculation in a constant variable before the loop and change the calculation by this variable?

    No, I would not even call it a cache, because this would imply that it will be resolved once at runtime, nor does it occur. It would only be useful to do this in the whole expression if you know that a variable does not vary within the loop, which is not the case with i . Even this optimization can be applied by some compiler if it fits, but it should already be less common, and in this case will have a run-time operation and then the result will be used as a cache.

        
    23.04.2018 / 01:02