Reputation: 23
Sometimes I declare "one use" variables in my code for clarity. Does this affect dramatically the performance or can the compiler optimize it?
For example, I would tend to do:
int minVal = long_arithmetic_expresion();
int maxVal = even_longer_expression();
for (int i = minVal; i < maxVal; i++)
{
// Do stuff not related to minVal or maxVal
}
double part1 = 4*sqrt(something)* ... // Very long thing
double part2 = 5*sqrt(something else)* ... // Very long thing
double interestingValue = part1 / part2; // This is the only interesting variable for later
Rather than:
for (int i = long_arithmetic_expresion(); i < even_longer_expression(); i++)
{
// Do stuff not related to minVal or maxVal
}
double interestingValue = (4*sqrt(whatever)* ...) / (5*sqrt(something else)* ...);
This for loop would be contained in a function that will be called many times, so even small performance gain would be relevant in my case.
Note:
As it was quickly pointed out, there is a chance that even_longer_expression() could be evaluated at every step of the loop, which is of course not good. For clarity, my question relates to the fact of declaring one-use variables. I have added a bit more code after the loop. I refer to cases like the variables part1 and part2.
Upvotes: 2
Views: 212
Reputation: 5533
Unless you disable optimizations, the following codes would almost surely show absolutely the same performance on a modern compiler (given that expressions are obviously independent):
// save to temporary minVal variable
int minVal = long_arithmetic_expresion();
int maxVal = even_longer_expression();
for (int i = minVal; i < maxVal; i++) {
...
}
// avoid creating temporary minVal variable
int maxVal = even_longer_expression();
for (int i = long_arithmetic_expresion(); i < maxVal; i++) {
...
}
But the first version is often more readable =)
The reason is: copy propagation for variables of fundamental types is trivial to do for a compiler. So in the first version compiler would remove i = minVal
assignment.
Upvotes: 2
Reputation: 1
Does this affect dramatically the performance or can the compiler optimize it?
Totally depends:
If long_arithmetic_expresion()
and even_longer_expression()
are marked as constexpr
and not likely to change during runtime, the compiler can optimize out recurring calls to these functions.
Otherwise it might be better to use the variables being initialized once.
Upvotes: 3