Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory efficient way to initialize a String to be reused inside a loop

Tags:

java

string

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.

like image 225
Walter R Avatar asked Jul 21 '15 19:07

Walter R


People also ask

What are two ways to initialize a string?

String initialization can be done in two ways: Object Initialization. Direct Initialization.

How do you initialize a variable in a for loop in Java?

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.

Is it good to declare variable inside for loop in Java?

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'.


1 Answers

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.

like image 184
6ton Avatar answered Sep 29 '22 02:09

6ton