为什么下面的工作正常?

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

但是下面这个被认为是危险的/不正确的:

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

有必要在循环之外声明变量吗?


当前回答

如果你想在循环外使用STR;在外面宣布。否则,第二版就可以了。

其他回答

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

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

因此,由于str不在循环之外使用,因此str的最小作用域是在while循环内。

因此,答案强调str绝对应该在while循环中声明。没有如果,没有并且,没有但是。

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.

编辑:(在答案下面注入我的评论)

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.

如果你不需要在while循环之后使用str(范围相关),那么第二个条件,即。

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

如果你只在条件为真时才在堆栈上定义一个对象,那就更好了。也就是说,如果你需要,就使用它

根据谷歌Android开发指南,变量范围应该是有限的。请查看此链接:

极限变量范围

我认为回答你的问题最好的资源是下面的帖子:

在循环前或循环中声明变量的区别?

根据我的理解,这个东西是语言依赖的。IIRC Java优化了这一点,所以没有任何区别,但JavaScript(例如)将在每次循环中完成整个内存分配。特别是在Java中,我认为当完成分析时,第二个程序会运行得更快。

如果你想在循环外使用STR;在外面宣布。否则,第二版就可以了。