[英]Should variable declarations always be avoided in C++?
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. 此for循环将包含在将被多次调用的函数中,因此在我的情况下,即使很小的性能提升也很重要。
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. 正如很快指出的那样,有可能在循环的每个步骤都可以评估even_longer_expression() ,这当然不好。 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 .
我指的是变量part1和part2之类的情况 。
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. 如果将
long_arithmetic_expresion()
和even_longer_expression()
标记为constexpr
并且在运行时不太可能更改,则编译器可以优化对这些函数的重复调用。
Otherwise it might be better to use the variables being initialized once. 否则,最好使用一次初始化的变量。
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. 因此,在第一个版本中,编译器将删除
i = minVal
分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.