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

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

问题描述

为什么以下工作正常?

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 >循环,否则你不会问这个问题,因为在中声明它,而循环不会是一个选项,因为它不会编译。

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 在循环之外使用 在 while循环中

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

所以,重点是 那个 str 绝对应该在while循环中声明。没有ifs,no和s,no buts。

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.

编辑:(这是我在下面的评论中写的,但我认为这是值得的在任何情况下,正确的方法是正确地编写所有的代码,为您的产品建立一个性能要求,衡量您的最终结果。

(this is something that I wrote in a comment below, but I think it is worth making part of 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天全站免登陆