Thursday, September 17, 2009

The JVM and how it handles stack and heap spaces

A recent discussion was going on about whether we should be using variables with a for loop or not. Going on those lines i stumbled upon a few articles explaining about the same.

A key point noted in the first post is
"The JVM specification that says that a JVM uses a fixed-size array for storing the values of local variables used in a method and each local variable maps to an index in this array. A Java compiler calculates the size of this array during the compilation of a method and declares it in the generated bytecode for the method."

So looking at that we can say that we do not necessarily need to worry about space allocation when thinking in terms of local variables as it is pre defined at compile time and is stored in a fixed-size array. Hence even if you create a String within a for loop, only one space allocated within that fixed-size array will be used. And according to the last forum post, the last comment sums it all up;

  • Class objects, including method code and static fields: heap.
  • Objects, including instance fields: heap.
  • Local variables and calls to methods: stack

  • But one thing to note is that in Java 6 some objects maybe created on the stack
    due to the "escape analysis" optimization used within Java 6. More info on that can be found at;

    No comments:

    Post a Comment