I am working in Java code optimization. I'm unclear about the difference between String.valueOf
or the +""
sign:
int intVar = 1;
String strVar = intVar + "";
String strVar = String.valueOf(intVar);
What is the difference between line 2 and 3?
strVar1 is equvalent to strVar2, but using int+emptyString "" is not elegant way to do it.
using valueOf is more effective.
Even though answers here are correct in general, there's one point that is not mentioned.
"" + intVar
has better performance compared toString.valueOf()
orInteger.toString()
. So, if performance is critical, it's better to use empty string concatenation.See this talk by Aleksey Shipilëv. Or these slides of the same talk (slide #24)
From the point of optimization , I will always prefer the
String.valueOf()
between the two. The first one is just a hack , trying to trick the conversion of theintVar
into aString
because the + operator.Using
String.valueOf(int)
, or better,Integer.toString(int)
is relatively more efficient for the machine. However, unless performance is critical (in which case I wouldn't suggest you use either) Then""+ x
is much more efficient use of your time. IMHO, this is usually more important. Sometimes massively more important.In other words,
""+
wastes an object, butInteger.toString()
creates several anyway. Either your time is more important or you want to avoid creating objects at all costs. You are highly unlikely to be in the position that creating several objects is fine, but creating one more is not.