1
1. What you should be more concerned with here, is not efficiency, but scope. Generally, you should strive to keep your variables as locally scoped as possible. This means, if you only need x within the loop, you should define it within the loop.
你在这里应该更关心的不是效率,而是范围。通常,您应该尽可能地将变量保持为本地范围。这意味着,如果在循环中只需要x,则应在循环内定义它。
You get a number of benefits with keeping your variables as locally scoped as possible:
将变量保持为本地作用域可以获得许多好处:
- Your code will be much more readable to someone else
您的代码对其他人来说更具可读性
- You won't accidentally assign to, or use the value of a variable you defined further up in your code that is still in scope, thus minimizing errors in your program
您不会意外地分配或使用您仍在范围内的代码中进一步定义的变量的值,从而最大限度地减少程序中的错误
- Most importantly, the garbage collector will free up any memory used by the variable as soon as it goes out of scope, keeping your program's performance high, and memory usage low.
最重要的是,垃圾收集器一旦超出范围就会释放变量使用的所有内存,从而保持程序性能高,内存使用率低。
You can read up more on variable scope and best practices from Josh Bloch's excellent book, "Effective Java" (scope is discussed in items 13 and 45). You might also want to read item 55, which discusses why it is important to optimize judiciously.
您可以从Josh Bloch的优秀书籍“Effective Java”(范围在第13和45项中讨论)中阅读有关可变范围和最佳实践的更多信息。您可能还想阅读第55项,其中讨论了明智地优化的重要性。
2. For the second part of your question, see The Skeet's answer here.
2.关于问题的第二部分,请参阅Skeet的答案。
Here's an example:
这是一个例子:
public static void main(String[] args) {
for(int i=0; i
This outputs:
size: 2
i: 0
size: 4
i: 1
size: 4
i: 2
size: 8
i: 3
size: 0
Notice how getSize()
is called for every iteration of the loop. In your example, calling .length
won't make a huge difference, as the JIT runtime will know how to optimize this call. But imagine getSize()
was a more complex operation, like counting the number of rows in a database table. Your code will be super slow as every iteration of the loop will call getSize()
, resulting in a database roundtrip.
注意如何为循环的每次迭代调用getSize()。在您的示例中,调用.length不会产生巨大的差异,因为JIT运行时将知道如何优化此调用。但是想象一下getSize()是一个更复杂的操作,比如计算数据库表中的行数。您的代码将非常慢,因为循环的每次迭代都将调用getSize(),从而导致数据库往返。
This is when you would be better off evaluating the value before hand. You can do this and still retain minimal scope for size
, like this:
这是你最好先评估价值的时候。您可以执行此操作并仍保留最小的大小范围,如下所示:
public static void main(String[] args) {
for(int size = getSize(), i=0; i
Notice how getSize()
is only called once, and also, the size
variable is only available inside the loop and goes out of scope as soon as the loop completes.
注意getSize()只被调用一次,而且size变量只在循环内部可用,并且在循环完成后就会超出范围。