There should be no extra jvm overhead depending on where you declare a variable.
Why? I participated in writing a cross compiler for C back at university 15 years ago. Our compiler allocated the stack space for _all_ local variables within a method at once, just before the method was invoked and independent of their scope. It would be run time expensive to do it dynamically: we only moved the stack pointer once for all method variables no matter how many. If you allocate "on demand", you (=the compiler) must generate code to manage this and move the stack pointer for _each_ variable when encountered. It's actually quite simple: the compiler first parses the method and collects all the variable names and types. I don't remember how we handled method parameters/arguments and return types (I think they were allocated by the calling method before making the call). Remember that the method itself explicitly allocates objects (using new) on the heap, so only the variables referencing these objects (which are reference/pointer types) have to be considered. This information is stored in a lookup table (method name, method code address, stack size needed and for each variable its name, type and relative address (offset from the stack pointer at runtime)), which the compiler looks up when it needs to generate code for a method call or when generating code for the method itself. When a method is called the following happens: 1. the address of the code currently being executed is pushed on the stack 2. the stack pointer is moved to hold the local variables of the method to be called 3. the cpu jumps to the location of the method code and contiues execution from there 4. when the method accesses local variables it does so by their relative address (e.g. "i=4;" in byte code will be "put the value 4 at the memory location (current stack pointer-12)" 5. when the method returns it moves the stack pointer back pops the code address of the calling code, jumps to this address and continues execution. By the way, you need to work with relative addresses since you cannot determine how the programm will execute at compile time. (It might depend on the input. Also consider recursions: if a variable was stored on a fixed position its value would be overwritten). The approach that I have described, requires the compiler to parse the code twice (first creating the lookup table and then generating the byte code for the methods). There are other ways to do it, but I am sure the developers of the java compiler use at least this approach (and probably a better one). Hope this makes things a little clearer Regards Kim Lesden To change your membership options, refer to: http://www.sys-con.com/java/list.cfm
