I have a loop like the one below which has an invariant, here the never changing value of scaleEveryValueByTwo
. Can I rely on the compiler finding this invariant and not checking the condition in every iteration (essentially compiling to something anologous to the code at the bottom)?
void loadValuesFromDisk(const bool scaleEveryValueByTwo)
{
std::vector<MyValueType> xs;
while(fileHasNewValues())
{
auto x = loadNextValue();
if (scaleEveryValueByTwo)
{
x *= 2;
}
xs.push_back(x);
}
}
I can of course split this into two loops manually (see below) or put the scaling part in a separate function, but in many cases this makes the code much longer and in my opinion harder to read (for example if I have nested loops for all dimensions of 3D data I would duplicate all three lines of loop headers and up to six lines of curly braces).
void loadValuesFromDisk(const bool scaleEveryValueByTwo)
{
std::vector<MyValueType> xs;
while(fileHasNewValues())
{
auto x = loadNextValue();
xs.push_back(x);
}
if (scaleEveryValueByTwo)
{
for(auto &x : xs)
{
x *= 2;
}
}
}
I'm primarily interested if I can rely on this (or even better, enforce) this optimization for commonly used compilers like gcc or MSVC, not some exotic ones that might be missing optimization that are de facto standard in most compilers.
Earlier there used to be /Og (global optimization) in MSVC compiler, which are now enabled by default. My guess is other compilers also do that.
To know how the loop optimization is done, look into below link and search for "Loop optimization"
https://docs.microsoft.com/en-us/cpp/build/reference/og-global-optimizations?view=vs-2019
As this comes by default now, you can rely on compiler.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments