First of all, I ask those who have the phobia of "premature optimization" to spare me: I do not want to optimize anything, I'm just interested.
I read / observed two things, including in stackoverflow (now I can not find the link):
- For method calls, memory for all local variables is reserved "at the beginning" of the method, that is, even for variables declared in lower-level areas (I know that this is a bad formulation from a scientific point of view, for example, ignoring how the call mechanism works, etc.) .d., but I hope this is clear). Obviously, there are no scopes for the running program, they are only at the source code level for better readability, versatility, code structuring, informing the compiler of our intentions (for example, giving optimization tips, see below).
- One of the advantages of declaring variables in the smallest possible area (that is, the highest level where they are still needed) is that "the compiler can reuse memory for other temporary variables (in other blocks)." It sounds clear and logical to me.
I'm curious that the / JIT / compiler can really optimize something and that it cannot.
Here is the following method (suppose variables are actually used, so for this reason they cannot be optimized):
// The method does many (useful) things, but these were cut here public void myMethod() { int var1 = 1; ... // do work if (something) { int var2 = 2; int var3 = 3; ... // do work } int var4 = 4; int var5 = 5; ... // do work }
1.) Can the compiler detect that the space for var2 and var3 can be reused for var4 and var5 ? I donโt remember seeing such things in disassembled byte codes.
2.) Is the code method above equivalent to the case where the end of the method is placed in {} too?
public void myMethod() { int var1 = 1; ... // do work if (something) { int var2 = 2; int var3 = 3; ... // do work } { int var4 = 4; int var5 = 5; ... // do work } }
Finally, consider a simpler case:
public void myMethod() { int var1 = 1; ...
3.) In this case, is it possible to use var1 memory for var4 (or var5 )? That is, in this case it is enough that the method has memory for two local int variables, and not for three.
(I know that in theory these are obvious cases for the compiler, but sometimes I skip things, for example, why the compiler cannot do anything or do something.)