在循环内部或外部声明变量 [英] Declaring variables inside or outside of a loop

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

问题描述

为什么以下工作正常?

String str;
while (condition) {
    str = calculateStr();
    .....
}

但据说这个是危险的/不正确的:

But this one is said to be dangerous/incorrect:

while (condition) {
    String str = calculateStr();
    .....
}

是否需要在循环外声明变量?

Is it necessary to declare variables outside the loop?

推荐答案

局部变量的作用域应该总是尽可能的小.

在你的例子中,我假设 str notwhile 循环之外使用,否则你不会问这个问题,因为声明while 循环中的它不是一个选项,因为它不会编译.

The scope of local variables should always be the smallest possible.

In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.

因此,由于str不在循环外使用,str的最小可能范围是while 循环.

So, since str is not used outside the loop, the smallest possible scope for str is within the while loop.

所以,答案是强调 str 绝对应该在 while 循环中声明.没有如果,没有和,没有但是.

So, the answer is emphatically that str absolutely ought to be declared within the while loop. No ifs, no ands, no buts.

唯一可能违反此规则的情况是,由于某种原因,每个时钟周期都必须从代码中挤出是至关重要的,在这种情况下,您可能需要考虑在外部范围内实例化某些内容并重用它而不是在内部作用域的每次迭代中重新实例化它.但是,这不适用于您的示例,因为 java 中字符串的不变性:始终会在循环开始时创建 str 的新实例,并且必须在循环结束时将其丢弃,因此有不可能在那里优化.

The only case where this rule might be violated is if for some reason it is of vital importance that every clock cycle must be squeezed out of the code, in which case you might want to consider instantiating something in an outer scope and reusing it instead of re-instantiating it on every iteration of an inner scope. However, this does not apply to your example, due to the immutability of strings in java: a new instance of str will always be created in the beginning of your loop and it will have to be thrown away at the end of it, so there is no possibility to optimize there.

(在答案下面插入我的评论)

(injecting my comment below in the answer)

无论如何,正确的做事方法是正确编写所有代码,为您的产品建立性能要求,根据此要求衡量您的最终产品,如果不满足,则进行优化.通常最终会发生的事情是,您会找到方法在几个地方提供一些很好的和正式的算法优化,从而使我们的程序满足其性能要求,而不必遍历整个代码库并调整和破解以便在这里和那里压缩时钟周期.

In any case, the right way to do things is to write all your code properly, establish a performance requirement for your product, measure your final product against this requirement, and if it does not satisfy it, then go optimize things. And what usually ends up happening is that you find ways to provide some nice and formal algorithmic optimizations in just a couple of places which make our program meet its performance requirements instead of having to go all over your entire code base and tweak and hack things in order to squeeze clock cycles here and there.

这篇关于在循环内部或外部声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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