In the code like:
for(int i=0; i<1000000; i++){
String abc = "blahblahblah";
abc = abc + foo();
//save abc to file
}
should I declare abc before this loop, or is the code optimized in a way that make this difference irrelevant?
In the code like:
for(int i=0; i<1000000; i++){
String abc = "blahblahblah";
abc = abc + foo();
//save abc to file
}
should I declare abc before this loop, or is the code optimized in a way that make this difference irrelevant?
If you are only going to use that variable inside of the loop, it is better to declare it inside. That way when you move onto the next iteration of the loop the memory used can be cleared up. Otherwise you would have to wait until the end of the method it was declared in, or for when the Object
it is a member of becomes eligible for garbage collection. This is subtly different for primitive variables (as apposed to your String
object) which will always be cleared up after the method ends anyway.
In other words, the scope of a variable should always be as small as practically possible to conserve memory (as well as other reasons).
See this answer for more details.
As for performance in speed, there shouldn't be any difference between declaring it inside the loop or outside. As confirmed by bytecode analysis here, and a comprehensive logical analysis here.
I hope this helps.