Home > OS >  When is Java variable created in memory?
When is Java variable created in memory?

Time:11-06

I am wondering when is Java creating variables during runtime (when a function is called). Please see the examples below and answer whether those are one the same.

void function someFunction(boolean test) {
    if (!test) {
        return;
    }
    int[] myVar = new int[1000000];
    ...
}
void function someFunction(boolean test) {
    int[] myVar = new int[1000000];
    if (!test) {
        return;
    }
    ...
}

I wouldn't like so spend time allocating memory only for it to be deallocated moments later, so I need to know whether Java will allocate memory needed for a certain variable (or array) needed by a function at the very beginning of that function, regardless of where the declaration happened, or will it allocate memory when it reaches the point of declaration.

EDIT:

I'm terribly sorry for confusion I'm causing. When I say variable I mean object.

CodePudding user response:

Probably at the point of method entry. It is a common compiler optimization to allocate a stack frame large enough to contain all locals. If that's so, it's pretty much a single subtraction to allocate space for them all. But you'd have to examine the bytecode to be sure.

However, in this:

int[] myVar = new int[1000000];

the 'variable' is a single reference, taking up 4 or 8 bytes. The object to which the variable refers is allocated at the point the initialization is encountered in execution, by the execution of the 'new' operator.

I suspect you need to read up on the distinction between variables and objects.

CodePudding user response:

In general, the Java compiler is a bit dumb in its compilation since it leaves the optimization up to the runtime JVM. As such, the compilation is mostly a straightforward translation of source code into bytecode.

https://godbolt.org/z/5xT3KchrW

In this case with the OpenJDK 17.0.0 compiler, the allocation of the array is done roughly at the same point in the bytecode as where the source code indicates.

However, the local variable of the pointer to the array is "allocated" at the time the method is called via registers. While the JVM uses a stack frame in a way very similar to C/C , on Android's Dalvik they instead use registers to hold local variables so it isn't ever actually "allocated" at all in memory (a design decision due to the focus on ARM -- with it's plentiful registers -- rather than x86 -- which is infamous for its lack of registers.

  •  Tags:  
  • java
  • Related