Does assignment operator use memory in Java?

I have two lines as shown below:

"yes", "no" .

Now I would like to compare these lines in two ways:

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

  • Assigning lines to some variable: Example:

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

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

+7
java variable-assignment
source share
3 answers

There is a very insignificant difference (actually insignificant, we are talking about micro-optimization here), since the string should be stored in a local variable that takes this extra bit of memory on the stack stack of the corresponding method. While the constants are actually stored in a constant pool and shared. With probable JVM optimization based on the number of calls, this will not make any difference.

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

+14
source share

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

The assignment operator never uses memory (except in cases of autoboxing: Integer number = 42 ). A local variable declaration may allocate memory on the stack (if necessary), but you should prefer code readability.

+9
source share

Depending on the compiler, it may take 2 extra references to objects on the stack. They are small enough, you can usually ignore them if you did not profile your application and you notice a problem there (very unlikely).

yes .equals (no)

This situation is unlikely to be in real code, since you already know if 2 literals are the same or not.

+6
source share

All Articles