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:
- The calculation "(3600 / 1000)" will be executed repeatedly during the 100 times of the loop?
- 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?
- 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.
– RHER WOLF