I'm using a couple of Strings in my code that are going to be reused within a loop and I'm wondering what would be the best way to initialize the String variables to improve memory usage:
// Just for sample purposes I will declare a Map, but the same thing
// applies for an ArrayList, Database Set, etc. You get the point.
Map<String, String> sampleMap = getMap();
int mapSize = sampleMap.size();
// String initialization
String a;
String b = new String();
String c = "";
for(int i = 0; i < mapSize; i++){
a = sampleMap.get(i);
b = someFunc(a);
c = anotherFunc(a);
// Do stuff with all the Strings
}
After the loop, the Strings are no longer used.
I'm using a couple of Strings in my code that are going to be reused within a loop
No, you're not. You're using a few string variables that are going to be reused within the loop. The actual strings aren't. Here's the body of the loop that you posted:
a = sampleMap.get(i);
b = someFunc(a);
c = anotherFunc(a);
The values of a
, b
and c
from previous iterations (or the values before the first iteration) are completely ignored within the body of the loop. Any value you assign before the loop is at best irrelevant, and at worst distracting and/or costly in efficiency. (If you use an empty string, and for some reason none of the rest of the VM ever uses an empty string, you're introducing one for no reason.)
I would recommend following 6ton's advice, and introducing the variables within the loop to start with, for the sake of readability - it won't affect your memory efficiency.
See more on this question at Stackoverflow