Search code examples
javamemorystack-frame

Size taken by stack frame


Java stack create new frame for every method call, But does this frame takes memory on the stack?

To clarify on my question :

public void oneWay()
{
  System.out.println("start");
  get1();
}

private void get1()
{
  System.out.println("get1");
  get2();
}

private void get2()
{
  System.out.println("get2");
}

Output of this is same as :

public void anotherWay()
{
  System.out.println("start");
  System.out.println("get1");
  System.out.println("get2");
}

But does second snippet takes more memory on stack or equal? In short, does stack frame take memory?

EDIT : How much memory does a stack frame take? Is there any specification by Sun, now Oracle?


Solution

  • As stated in Inside the Java Virtual Machine,

    The stack frame has three parts: local variables, operand stack, and frame data. The sizes of the local variables and operand stack, which are measured in words, depend upon the needs of each individual method. These sizes are determined at compile time and included in the class file data for each method. The size of the frame data is implementation dependent.

    When the Java virtual machine invokes a Java method, it checks the class data to determine the number of words required by the method in the local variables and operand stack. It creates a stack frame of the proper size for the method and pushes it onto the Java stack.