java - Does adding scope {} brackets to let variables go out of scope have the same effect as calling and ending a function or some sort of empty loop? -


i wonder if possible let variables go out of scope while adding brackets around piece of code , if it's different other ways let variables go out of scope:

0) adding brackets:

private void methodexample() {     {         int example = 5;     }     //variable "example" out of scope } 

1) function call:

private void methodexample() {             justmakeitamethod();     //variable "example" out of scope }  private void justmakeitamethod() {         int example = 5; } 

2) loop ends like:

private void methodexample() {     {         int example = 5;     } while (false);     //variable "example" out of scope } 

does way variables go out of scope respect stack differ per example?

the reason thought of this: [disclaimer know case of premature optimization]i have low level function in have many different small independent parts of code different functionality, not enough in opinion make different function require function call overhead, enough parts rather have variables go out of scope.

the behavior might differ depends on whether have interpreted or jit-compiled frame. in jit-compiled frame object can marked free after last usage of variable if it's still in scope. see this answer example. in interpreted frames still reside in stack frame variable slot after scope ends. on other hand compiler reuses variable slots freed scope ends. can lead interesting results interpreted frames:

public class lvtest {     @override     protected void finalize() {         system.out.println("finalized");     }      public static void main(string[] args) throws interruptedexception {         {             lvtest t = new lvtest();         }         system.out.println("gc!");         system.gc();         thread.sleep(1000);         system.out.println("gc!");         system.gc();         thread.sleep(1000);         system.out.println("gc!");         system.gc();         thread.sleep(1000);         system.out.println("assign new var!");         int = 5;         system.out.println("gc!");         system.gc();         thread.sleep(1000);         system.out.println("finish");     } } 

the output this:

gc! gc! gc! assign new var! gc! finalized finish 

so no matter how many times collect garbage our out-of-scope object not finalized. after assign new variable reuses same variable slot, can free original variable. method jit-compiled, finalized message appear earlier.

in case "scope end" compiled nothing in bytecode, jvm not know close curly brace. if think code executed in interpreted frame, it's more safe assign null variable after usage using block , hope new variables created after it. though if have part of method executes long time , not use created variable, better split method smaller parts. in jit-compiled frame should not optimize @ all: jit-compiler smart.


Comments