在循环之前或在循环中声明变量之间的区别? [英] Difference between declaring variables before or in loop?

查看:31
本文介绍了在循环之前或在循环中声明变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道,一般来说,在循环之前声明一个丢弃变量,而不是在循环内重复,是否会产生任何(性能)​​差异?一个(毫无意义) 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);
}

ab 哪个更好?

我怀疑重复的变量声明(例如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.

推荐答案

ab 哪个更好?

从性能的角度来看,您必须对其进行衡量.(在我看来,如果你能衡量一个差异,编译器就不是很好).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆