Reputation: 4371
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?
Upvotes: 7
Views: 232
Reputation: 33544
- The defines the reference everytime the loop iterates, but the scope of the reference is attached only to that iteration.
- Consider that you have declared a reference outside the loop, but assign object to it inside the loop, then the reference remains the same , but it reference new object of that type in every iteration.
Upvotes: 1
Reputation: 66677
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.
Upvotes: 7
Reputation: 533880
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.
Upvotes: 4
Reputation: 877
Its defined every time. There is no optimization for that (to my knowledge).
Upvotes: 2