Imagine a function in those versions:
static int fibonacciIterative(int n) {
int previous = 0;
int current = 1;
for (int i = 1; i < n; i++) {
int temp = current;
current += previous;
previous = temp;
}
return current;
}
static int fibonacciIterative(int n) {
int previous = 0;
int current = 1;
int temp;
for (int i = 1; i < n; i++) {
temp = current;
current += previous;
previous = temp;
}
return current;
}
The only difference is that the variable temp
is declared again and again in the loop of the first version, while it's declared once outside the loop in the second version. Is there any difference in the resulting bytecode regardless the significance? How is the compiler handling such cases and can the second version be regarded as an optimized first version?
Variables aren't declared at all at the bytecode level (ignoring the usual caveats about debug metadata). Instead, each method has a table of up to 65,535 "slots" that the bytecode can store and retrieve values from. The compiler will assign each variable a slot, making sure not to reuse slots for variables with overlapping liveness ranges.
So in your example, I would expect the only difference to be that temp
and i
get assigned slots in a different order, but the bytecode is otherwise identical.
That being said, this is even more irrelevant than you might think, because bytecode is not what is executed (most of the time) by the JVM. Instead, it is merely an abstraction. For any code where performance actually matters, the JVM will do static analysis on your code and then optimize it and compile it to native code, so trivial differences in bytecode encoding are completely meaningless anyway.