Which is optimal?

前端 未结 8 515
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 21:23

Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?

eg

相关标签:
8条回答
  • 2020-12-11 22:00

    The most optimal way to traverse a list is to use an Iterator.

    for (Iterator iter=list.iterator(); iter.hasNext();) {
      System.out.println(iter.next());
    }
    
    0 讨论(0)
  • 2020-12-11 22:02

    The Java compiler determines how many "slots" it needs in the stack frame based on how you use local variables. This number is determined based on the maximum number of active locals at any given point in the method.

    If your code is only

    int value;
    for (...) {...}
    

    or

    for (...) {
       int value;
       ...
    }
    

    there's only one slot needed on the runtime stack; the same slot can be reused inside the loop regardless of how many times the loop runs.

    However, if you do something after the loop that requires another slot:

    int value;
    for (...) {...}
    int anotherValue;
    

    or

    for (...) {
       int value;
       ...
    }
    int anotherValue;
    

    we'll see a difference - the first version requires two slots, as both variables are active after the loop; in the second example, only one slot is required, as we can reuse the slot from "value" for "anotherValue" after the loop.

    Note: the compiler can be smarter about optimizations depending on how the data is actually used, but this simple example is meant to demonstrate that there can be a difference in stack frame allocation.

    0 讨论(0)
提交回复
热议问题