Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Assigning a variable its current value?

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?

like image 915
user2968401 Avatar asked Jun 18 '15 07:06

user2968401


2 Answers

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.

like image 147
Sharon Ben Asher Avatar answered Oct 06 '22 00:10

Sharon Ben Asher


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.

like image 28
maaartinus Avatar answered Oct 05 '22 23:10

maaartinus