Java: assigning a variable the current value?

If I have an empty string,

String s = "";

      

and reassign it

s = "";

      

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

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

      

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

+3


source to share


4 answers


the cost of calling the isEmpty () method (allocating new space on the thread stack, etc.) negates any benefit. if you want to assign an empty string to this variable, it is most advisable to do it without an if statement.



+4


source


If there is real logic between initialization and the point at which you re-assign ""

, the compiler probably won't be able to optimize it. But it's okay if it isn't, because the reassignment won't take any significant amount of time. In theory, if that were the case, the Just-In-Time (JIT) compiler in the JVM (well, the Oracle JVM anyway) would try to optimize it (if it could) if it turned out to be a hot spot in code.



0


source


Java uses String Pools, which often creates a string, and in case of reusing the same string, one of them is selected to assign it instead of creating a new String Object. There is also an intern method in the String class that ensures that the string is fetched from the pools. eg,

s="".intern();

      

although rarely required (makes it clear to the code that you want a pooled string to be available), the java runtime automatically does the trainee job because strings are immutable.

The compiler does not optimize the reassignment if it finds the previous value. There is also no need to optimize it, it would be very minor to reassign it compared to overlaying it before reassigning it.

0


source


Don't micro-pessimize your code.

s = "";

      

The assignment is JIT translated into a move to a register, where the source is probably also in the register (in the loop, such an optimization is done if you haven't run out of registers). So the fastest instruction, taking only 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 becomes inline. But there is still indirect memory from String

to her value.length

. Not bad, but more expensive than the simple method. Then a conditional branch that can take dozens of cycles if the result cannot be predicted by the CPU. If not, you're still in luck and JIT can replace it with conditional motion. Whatever happens, it can never be faster than simple code.

Adding

In theory, you can hope that the JIT learns that the two are equivalent and replaces pessimized idle. But these two options are not equivalent. You will need to use

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

      

as there may be a different empty string than interned (i.e. compile time constant ""

). Anyway, I hope we agree that the above snippet is something that no one should ever use.

0


source







All Articles