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.

http://rmathew.blogspot.com/2007/01/local-variables-in-java.html
http://www.coderanch.com/t/416620/Beginning-Java/java/What-stored-Stack-Heap
http://forums.sun.com/thread.jspa?messageID=2406140

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;

    http://java.sun.com/javase/6/webnotes/6u14.html

    No comments:

    Post a Comment