我一直想知道,在一般情况下,在循环之前声明一个丢弃的变量,而不是在循环内部重复,使任何(性能)差异? 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案例特别感兴趣。


当前回答

一位同事更喜欢第一种形式,说这是一种优化,更喜欢重用声明。

我更喜欢第二种(试着说服我的同事!);-)),已读到:

它将变量的范围缩小到需要的地方,这是一件好事。 Java进行了足够的优化,在性能上没有显著差异。IIRC,也许第二种形式更快。

无论如何,它属于依赖于编译器和/或JVM质量的过早优化的类别。

其他回答

我一直认为,如果你在循环中声明变量,那么你就是在浪费内存。如果你有这样的东西:

for(;;) {
  Object o = new Object();
}

然后,不仅需要为每次迭代创建对象,还需要为每个对象分配一个新的引用。看起来,如果垃圾收集器很慢,那么就会有一堆需要清理的悬空引用。

然而,如果你有这样的情况:

Object o;
for(;;) {
  o = new Object();
}

然后,您只需创建一个引用,并每次为它分配一个新对象。当然,它可能需要更长的时间才能超出作用域,但这时只需要处理一个悬空引用。

我把A和B的例子各运行了20次,循环了1亿次。(jvm - 1.5.0)

A:平均执行时间:0.074秒

B:平均执行时间:0.067秒

令我惊讶的是B稍微快一点。 尽管现在的计算机速度很快,但很难说你是否能准确地测量这一点。 我也会用A的方式来编码,但我想说这并不重要。

我的做法如下:

如果变量类型为simple (int, double,…)我更喜欢变种b(里面的)。 原因:减少变量的范围。 如果变量的类型不简单(某种类或结构),我更喜欢变量a(外部)。 原因:减少与医生的通话次数。

从性能的角度来看,外部(要好得多)。

public static void outside() {
    double intermediateResult;
    for(int i=0; i < Integer.MAX_VALUE; i++){
        intermediateResult = i;
    }
}

public static void inside() {
    for(int i=0; i < Integer.MAX_VALUE; i++){
        double intermediateResult = i;
    }
}

两个函数我都执行了10亿次。 Outside()耗时65毫秒。Inside()耗时1.5秒。

以下是我在。net中编写和编译的内容。

double r0;
for (int i = 0; i < 1000; i++) {
    r0 = i*i;
    Console.WriteLine(r0);
}

for (int j = 0; j < 1000; j++) {
    double r1 = j*j;
    Console.WriteLine(r1);
}

这是我从。net Reflector中得到的,当CIL被渲染回代码时。

for (int i = 0; i < 0x3e8; i++)
{
    double r0 = i * i;
    Console.WriteLine(r0);
}
for (int j = 0; j < 0x3e8; j++)
{
    double r1 = j * j;
    Console.WriteLine(r1);
}

So both look exactly same after compilation. In managed languages code is converted into CL/byte code and at time of execution it's converted into machine language. So in machine language a double may not even be created on the stack. It may just be a register as code reflect that it is a temporary variable for WriteLine function. There are a whole set optimization rules just for loops. So the average guy shouldn't be worried about it, especially in managed languages. There are cases when you can optimize manage code, for example, if you have to concatenate a large number of strings using just string a; a+=anotherstring[i] vs using StringBuilder. There is very big difference in performance between both. There are a lot of such cases where the compiler cannot optimize your code, because it cannot figure out what is intended in a bigger scope. But it can pretty much optimize basic things for you.