Java: Assigning a variable its current value?

1k Views Asked by At

If I have a string that is currently empty

String s = "";

and reassign it

s = "";

is it bad it I don't do it like this?

if(!s.isEmpty()){
   s = "";
}

or will the compiler pick up on it and optimize for me?

3

There are 3 best solutions below

1
On BEST ANSWER

the cost of calling the method isEmpty() (allocating new space in the thread stack etc) negate any gains. if you want to assign an empty String to the variable, its most efiicient to do so without the if statement.

0
On

Do not micro-pessimize your code.

s = "";

The assignment gets translated by JIT into a move into register, where the source most probably resides in register as well (in a loop, such an optimization gets done unless you run out of registers). So it's the fastest instruction taking just one cycle and current Intel can execute 4 of them in parallel.

if(!s.isEmpty()){
   s = "";
}

The function call is not a problem, as it gets inlined. But there's still a memory indirection from the String to it's value.length. Not bad, but already way more expensive than the simple way. Then a conditional branch, which can take tens of cycles, unless the outcome can be predicted by the CPU. If not, you still may be lucky and the JIT may replace it by a conditional move. Whatever happens, it can never be faster than the simpler code.

Addendum

In theory, you could hope that the JIT finds out that the two variants are equivalent and replaces the pessimized one by the simple one. But these two variants are not equivalent. You'd need to use

if (s != "") {
    s = "";
}

instead as there may be other empty string than the interned one (i.e., the compile time constant ""). Anyway, I hope that we agree that the above snippet is something nobody should ever use.

0
On

If there's any real logic between the initialization and the point at which you assign "" again, the compiler probably won't be able to optimize it out. But it's fine if it doesn't, because the reassignment isn't going to take any significant time. In theory, if it did, the Just-In-Time compiler (JIT) in the JVM (well, Oracle's JVM, anyway) would try to optimize it (if it could) if it ended up being a "hot spot" in the code.