Do unused local variables in a method acquire memory in JVM?

前端 未结 5 778
感情败类
感情败类 2020-12-15 04:17

I came across this post in SO Do uninitialized primitive instance variables use memory?

It states \"In Java, does it cost memory to declare a class level instance va

5条回答
  •  情话喂你
    2020-12-15 04:55

    The way a primitive variable is stored in a local variable (in bytecode) is with:

    istore(for int values), dstore(for double values), fstore(for float values) and so on..

    Each of them pop the top of the operator stack and write it into local variable numbered Var. So, an operator needs to push the value that need to be stored, on the top of the operator stack, just before the store operation. They works in pair.

    So, if you do something like:

    int i;
    //...
    i = 12;
    //...
    

    Your compiler will push the integer 12 in the top of the operator stack and then pop this value and write it in a local variable only at the variable initialization time.

    //...
    bipush 12
    istore_1 1
    

    If you never initialize your variable, the compiler cannot push a value at the top of the operator stack so the store operation is impossible. it's not a compiler optimization, it's just the way bytecode works. So, your compiler just removes your line.

    Take this simple example:

    public static void main(String[] args) {
        int i;
        int j = 10;
        System.out.println(j);
        i = 12;
        System.out.println(i);
    }
    

    And look when the local variable i is initialized:

    public static void main(String[] p0) {
        bipush 10
        istore_2 2
        getstatic PrintStream System.out
        iload_2 2
        invokevirtual void PrintStream.println(int)
        bipush 12
        istore_1 1
        getstatic PrintStream System.out
        iload_1 1
        invokevirtual void PrintStream.println(int)
        return
    }
    

    You may notice that the local variable # 2 is used before the local variable # 1.

    Take this last example:

    public static void main(String[] args) {
        int i;
        int j = 10;
        System.out.println(j);
    }
    

    The bytecode would be:

    public static void main(String[] p0) {
        bipush 10
        istore_2 2
        getstatic PrintStream System.out
        iload_2 2
        invokevirtual void PrintStream.println(int)
        return
    }
    

    The local variable 1 is never used and something is stored in the local variable 2. Because of that, 2 x 32 bits would be allocated here even if the local variable 1 is not used.

    edit: (from Hot Licks comment)

    The JVM interpreter will allocate as many local slots as are specified in the method header. They are allocated whether they are used or not. Long and double values get two slots (even though the slots are 64 bits and only one is used in most modern implementations).

    A non-initialized int local variable would required 32 bits here, for example.

提交回复
热议问题