Should I avoid operations between constants in a loop?

Asked

Viewed 85 times

6

In C++ there is some sort of optimization or cache that prevents the same mathematical operation between constants to be repeated, mainly 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 fictitious, but is only to illustrate the situation. It could be a loop millions of times with hundreds of calculations involving repeated constants.

So I ask:

  1. The calculation "(3600 / 1000)" will be executed repeatedly during the 100 times of the loop?
  2. In this way, to avoid loss of performance I should store this calculation in a constant variable before the loop and exchange the calculation for this variable?
  3. Or I don’t have to worry about it because C++ gives a "way" to optimize these situations automatically to prevent performance loss?

I believe that this doubt is pertinent, because it involves the style of programming that should be adopted.

  • Roger, that’s called constant expression. C++ compilers that identify the need to operate two known integers at compile time normally operate them and put the result in place of the operation to thus generate the executable in such a way that performance is gained running by reducing instructions executed.

1 answer

6


The calculation "(3600 / 1000)" will be executed repeatedly during the 100 loop times?

There are no guarantees that occur, but in practice it will be optimized yes and the operation will be resolved at compile time generating no cost in execution.

In this way, to avoid loss of performance I should store this calculation in a constant variable before the loop and exchange the calculation for this variable?

No, I wouldn’t even call it a cache, because it would imply that it will be solved 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 of i. Even this optimization can be applied by some compiler if it fits, but it should already be less common, and in this case it will have a run time operation and then the result will be used as a cache.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.