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.
String initialization can be done in two ways: Object Initialization. Direct Initialization.
Java Simple for Loop A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts: Initialization: It is the initial condition which is executed once when the loop starts.
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'.
Reduce the scope of your variables to restrict them to where they are used:
// 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();
for(int i = 0; i < mapSize; i++){
String a = aFunc();
String b = sampleMap.get(i);
String c = anotherFunc();
// Do stuff with the Strings
}
There is no performance benefit of declaring the variables outside the loop.
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