我一直想知道,在一般情况下,在循环之前声明一个丢弃的变量,而不是在循环内部重复,使任何(性能)差异? Java中的一个(非常无意义的)例子:

A)循环前声明:

double intermediateResult;
for(int i=0; i < 1000; i++){
    intermediateResult = i;
    System.out.println(intermediateResult);
}

B)声明(重复)内部循环:

for(int i=0; i < 1000; i++){
    double intermediateResult = i;
    System.out.println(intermediateResult);
}

哪个更好,a还是b?

我怀疑重复的变量声明(例b)在理论上会产生更多的开销,但编译器足够聪明,所以这无关紧要。例b的优点是更紧凑,并且将变量的作用域限制在使用它的地方。尽管如此,我还是倾向于根据示例a编写代码。

编辑:我对Java案例特别感兴趣。


当前回答

作为一般规则,我将变量声明在最内部的可能范围内。如果你不在循环外使用intermediateResult,那么我会用B。

其他回答

如果你在lambda中使用变量,在c#中是有区别的。但一般来说,编译器基本上会做同样的事情,假设变量只在循环中使用。

鉴于它们基本上是相同的:请注意,版本b对读者来说更明显的是,变量不是,也不能在循环之后使用。此外,版本b更容易重构。在版本a中,将循环体提取到它自己的方法中更加困难。而且,版本b向您保证这样的重构没有副作用。

因此,版本a让我很恼火,因为它没有任何好处,而且它让我更难理解代码……

A)比B).........更安全想象一下,如果你在循环中初始化结构而不是'int'或'float'然后呢?

就像

typedef struct loop_example{

JXTZ hi; // where JXTZ could be another type...say closed source lib 
         // you include in Makefile

}loop_example_struct;

//then....

int j = 0; // declare here or face c99 error if in loop - depends on compiler setting

for ( ;j++; )
{
   loop_example loop_object; // guess the result in memory heap?
}

您肯定会遇到内存泄漏的问题!因此,我认为“A”是更安全的赌注,而“B”是容易受到内存积累的影响,特别是工作在近源库中。你可以在Linux上使用“Valgrind”工具检查,特别是子工具“Helgrind”。

我认为b是更好的结构。在a中,intermediateResult的最后一个值在循环结束后保留。

编辑: 这与值类型没有太大区别,但引用类型可能会有些重要。就我个人而言,我喜欢尽快解除对变量的引用以进行清理,b为你做了这件事,

即使我知道我的编译器足够聪明,我也不喜欢依赖它,而是使用a)变体。

b)变体对我来说只有当你迫切需要使intermediateResult在循环体之后不可用时才有意义。但我无法想象这种绝望的情况,无论如何....

编辑:Jon Skeet提出了一个非常好的观点,表明在循环中声明变量可以产生实际的语义差异。

这是个有趣的问题。从我的经验来看,当你为代码争论这个问题时,有一个终极问题需要考虑:

为什么变量需要是全局的?

It makes sense to only declare the variable once, globally, as opposed to many times locally, because it is better for organizing the code and requires less lines of code. However, if it only needs to be declared locally within one method, I would initialize it in that method so it is clear that the variable is exclusively relevant to that method. Be careful not to call this variable outside the method in which it is initialized if you choose the latter option--your code won't know what you're talking about and will report an error.

另外,作为旁注,不要在不同的方法之间重复局部变量名,即使它们的目的几乎相同;这让人很困惑。