jeudi 8 avril 2021

Should we always rely on compiler optimizations nowadays?

It used to be a good practice to write code like this:

int var = 0, var1 = 0; //declare variables outside the loop not to create them every time we go into for
auto var2 = somefunc(/*some params*/); 
for (int i = 0, size = vec.size(); i < size; ++i)
{
    //do some calculation, use var, var1, var2
}

But now all(?) modern compilers will optimize it for you, and if you write:

for (int i = 0; i < vec.size(); ++i)
{
    //do something
    int var = /*some usage*/; //declare where you need it for better readability
    //do something     
    int var1 = /*some usage with call to somefunc(/*some params*/) */; //declare where you need it for better readability
    //do something
}

The compiler will optimize it to be the same as the first snippet (or even better).

So, should we always rely on the compiler to optimize variable allocation, etc, to write code that is easier to read for other programmers?

Disclaimer: this is not an opinion-based question. I don't have experience with many compilers, and I don't have experience in using compiler optimization options, so I expect people with experience to answer here, something like "I've worked with so many compilers, yes, nowadays they are all smart and we don't need to think about where to declare variables", or "oh, I've run into some compilers that didn't do those kind of optimizations, so we still need to think about it", or something about experience of usage of optimization options.

Aucun commentaire:

Enregistrer un commentaire