String in java, is it more efficient to create or assign?

Question:

Let's imagine that I have a String that I am going to assign a value to repeatedly within a loop, what would be more efficient to declare it previously and assign a value to it in each interaction or to do it directly within each iteration?

Example A:

String temp;
for (...) {
   temp = algo;

   // hacer algo
}

Example B:

for (...) {
   String temp = algo;

   // hacer algo
}

Answer:

In principle, good practices tell us that the ideal is that the variables have the smallest possible scope ( scope ) , to avoid unwanted effects, so all things being equal it is advisable to declare the variables within the loop.

In terms of performance, the Java compiler is smart enough that declaring the variable inside or outside has the same cost, so it is not a parameter to take into account.

There is one case where I would recommend declaring off, but it is the exception:

for (...) {
    String s=calcularValor();
    ... //operaciones con s
};

The calcularValor function always returns the same value. If the calculation is an expensive operation (reading a file, for example), it is preferable to use it once, although later we do not use the variable outside the loop.

Scroll to Top