I'm just curious.
suppose I define a reference inside a while/for loop.
does the JVM define this reference every iteration, or it's optimized to define it only once?
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
It's the result of JVM specifications... But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). It is the result of the JVM Soecification, not 'compiler optimization'.
Yes. you can declare a variable inside any loop(includes do while loop.
It defines every time and scoped to only that loop iteration.
As soon as loop iteration done, it is eligible for GC.
As Louis Wasserman commented, The variable will be reinitialized every time, but the memory space will probably get reused.
The reference is defined on each iteration. Once the code has been optimised to native code, it could be moved outside the loop so it doesn't have to have a performance impact. If you set this reference to a new
object each time, it may create a new object on each iteration unless that object creation has been optimised away also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With