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
}
In principle, good practices tell us that the ideal is for the variables to have the smallest scope possible , to avoid undesired effects, so all other 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 outside, but this is the exception:
The function
calcularValor
always returns the same value. If the calculation is an expensive operation (reading a file, for example), it is preferable to use it once, even if we do not use the variable outside the loop afterwards.Let's approach the problem from the point of view of the bytecode
I have created a test class, called
Test
:If we compile it and view its bytecode using
javac Test.java
andjavap -c Test.class
respectively, we will see:Now, let's change the code of
Test
:And let's see the resulting bytecode again:
The only thing that changes is the order of variables. Specifically, from
temp
andi
inside the loop. That is, the bytecode is the same . Knowing this, it is best to follow the best practices, which as already mentioned is to reduce the scope of the variable in question as much as possible. The best option is B.