Java: assigning a variable the current value?
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.
source to share
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.
source to share
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.
source to share