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

前端 未结 5 784
感情败类
感情败类 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:41

    Expanding slightly on the testcase from @JonKiparsky:

    public class StackSlotTest {
        public int bar(){
            int a;
            a = 5;
            System.out.println("foo");
            return a;
        }
    
        public int foo(){
            int x;
            int a;
            a = 5;
            System.out.println("foo");
            return a;
          }
    }
    

    I added the variable a to both methods, and added a set and use of it in both.

      public int bar();
        Code:
           0: iconst_5
           1: istore_1
           2: getstatic     #2                  // Field java/lang/System.out:Ljava/
    io/PrintStream;
           5: ldc           #3                  // String foo
           7: invokevirtual #4                  // Method java/io/PrintStream.printl
    n:(Ljava/lang/String;)V
          10: iload_1
          11: ireturn
    

    Above you see that the iload_1 bytecode loads the value of a to be returned. The second stack slot is referenced. (The first is the this pointer.)

      public int foo();
        Code:
           0: iconst_5
           1: istore_2
           2: getstatic     #2                  // Field java/lang/System.out:Ljava/
    io/PrintStream;
           5: ldc           #3                  // String foo
           7: invokevirtual #4                  // Method java/io/PrintStream.printl
    n:(Ljava/lang/String;)V
          10: iload_2
          11: ireturn
    

    In this case the value of a is loaded with iload_2, to access the third slot, because the second slot is occupied (sort of) by the (totally unused) variable x.

提交回复
热议问题