I have a friend who told me the following but I couldn't give a good reason why.
someArray =.........
int a;
for(int i=0; i < someArray; i++) {
a=someArray.get(i).length();
// Do something
}
He told me that he declared a
outside of the for loop in order to avoid frequent garbage collection.
I thought declaring a
inside of the for loop is more readable and thread safe.
However I couldn't disagree that different instances a
no of iteration will be garbage collected if it's declared inside of for loop.
Any advise for me?
Try decompiling both versions:
The resulting bytecode is identical, so there is no performance or behavioural difference.
As such, you should use the one which is more readable, and has variables in tighter scope: declare the variable inside the loop.
Garbage collection handles objects. What you have is a primitive local variable
a
which will be allocated on the stack.Therefore the whole premise of this question is wrong.
Since
a
is not an object which gets created with every loop iteration it will not be garbage collected at all.Local, non object data types like int, float, bool,... are being kept on a stack. If the variable is out of scope they will be popped from the stack.
In case
a
would be an object the reference to the object would be removed with every iterration causing the object itself to become not referenced anymore which means it will be GCed at some point in the future.More information: (Chapter 2.6) https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html