在循环之前或循环中声明变量之间的区别? [英] Difference between declaring variables before or in loop?
问题描述
我一直想知道,一般来说,在循环之前声明一个抛弃变量,而不是在循环内重复,是否会产生任何(性能)差异?
Java中的(毫无意义)示例:
I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (quite pointless) example in Java:
a)循环前声明:
double intermediateResult;
for(int i=0; i < 1000; i++){
intermediateResult = i;
System.out.println(intermediateResult);
}
b)声明(重复)内循环:
b) declaration (repeatedly) inside loop:
for(int i=0; i < 1000; i++){
double intermediateResult = i;
System.out.println(intermediateResult);
}
哪一个更好, a 或 b'/强>?
Which one is better, a or b?
我怀疑重复变量声明(例如 b )会在理论上产生更多的开销 ,但编译器很聪明足以让它无所谓。示例 b 具有更紧凑的优点,并将变量的范围限制为使用它的位置。不过,我倾向于根据示例进行编码 a 。
I suspect that repeated variable declaration (example b) creates more overhead in theory, but that compilers are smart enough so that it doesn't matter. Example b has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example a.
编辑: 我是特别感兴趣的是Java案例。
I am especially interested in the Java case.
推荐答案
哪个更好, a 或 b ?
从性能角度来看,您必须对其进行衡量。 (在我看来,如果你可以测量差异,编译器就不太好了。)
From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).
从维护的角度来看, b 更好。在尽可能最窄的范围内,在同一位置声明和初始化变量。不要在声明和初始化之间留下空洞,也不要污染你不需要的命名空间。
From a maintenance perspective, b is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.
这篇关于在循环之前或循环中声明变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!