Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the assignment operator consume memory in Java?

I have some two Strings as below:

"yes", "no".

Now, I would like to compare these Strings in two ways:

  1. Directly:
    Example: "yes".equals("no")

  2. By assigning the strings to some variable: Example:

    String string1 = "yes";
    String string2 ="no";
    string1.equals(string2);
    

In these two cases, is there any memory or performance difference?

like image 611
Saikiran Gosikonda Avatar asked Mar 21 '16 11:03

Saikiran Gosikonda


People also ask

What are the advantages of assignment operator in Java?

The basic advantage of compound assignment operators is that it saves a lot of code within the Java language program.

What are the two rules of assignment in Java?

In a Java assignment, the types of the variable and expression must match. For example, if one is a boole- an, the other must be also, and if one is a String, the other must be a String.

Does class occupy memory in Java?

Classes in Java Hence it has no physical existence. In simple words, classes do not occupy memory space.

How does assignment work in Java?

In Java, an assignment statement is an expression that evaluates a value, which is assigned to the variable on the left side of the assignment operator. Whereas an assignment expression is the same, except it does not take into account the variable.


3 Answers

There is a very minor difference (effectively negligible, we're talking micro-optimization here), since the string should be stored in a local variable which takes that extra bit of memory on the stack frame of the corresponding method. Whereas the constants are actually stored in the constant pool and shared. With the likely optimizations of the JVM based on the number of invocations, it won't make a difference.

Note that the bytecode would be the same if the variables were final or effectively final (assigned only once), since in this case they are treated as constants.

like image 107
M A Avatar answered Sep 22 '22 02:09

M A


Compiling these code snippets will result in the same bytecode. Hence, there is no memory consumption or performance difference.

The assignment operator never consume memory (except the case of autoboxing: Integer number = 42). Local variable declaration may allocate memory in stack (if it necessary), but you should prefer code readability.

like image 24
Vladimir Petrakovich Avatar answered Sep 24 '22 02:09

Vladimir Petrakovich


Depending on the compiler it might take the space of 2 additional object references on the stack, I guess. These are small enough you usually can ignore them unless you profiled your application and you spotted an issue there (very unlikely).

"yes".equals("no")

In real code there is hardly ever a situation like this, as you would already know if 2 literals are the same or not.

like image 43
Puce Avatar answered Sep 26 '22 02:09

Puce