Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

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

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 variable without initializing it? For example: Does int i; use any memory if I don't initialize it with i = 5;?"

My question is what in case of local variables, say i have a method foo()

public int foo(){

  int x;

//Write code which does not use/initialize x
}

Will the local variable x occupy memory?

Edit

Jon's Answer is

UPDATE: Doing a bit more research on this, I find this page which suggests to me that, although the compiled bytecode implies that space is allocated for x, it may indeed be optimized away by the jvm. Unfortunately, I find no complete description of the optimizations performed. Particularly, the JVM documentation chapter on compiling does not mention removing unused variables from the stack. So, barring further discoveries, my answer would be that it's implementation-dependent, but it seems like the sort of optimization that any self-respecting compiler would perform. Notice too that it doesn't matter that much that this is a local variable rather than a field - in fact, local variables are the ones most likely to be optimized away, since they are the easiest to analyze and eliminate. (precisely because they are local)

Let us see if can find more evidences which supports this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Class level / Instance level variables will be initialized to their default values automatically. So, yes, they will occupy some space when a class is initialized / instance created respectively.

As far as method local variables are concerned, No, if they are just declared but not initialized, then they will not use any space, they are as good as ignored by the compiler..

If your code was this :

public static void main(String[] args) {
    int i;  // ignored
    int j = 5;
    String s = "abc";
    String sNull; // ignored
}

Byte code :

  LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       6     0  args   [Ljava/lang/String;
            2       4     2     j   I
            5       1     3     s   Ljava/lang/String;
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...