I am working in Java code optimization. I\'m unclear about the difference between String.valueOf or the +\"\" sign:
int intVar = 1;
Well, if you look into the JRE source code, Integer.getChars(...) is the most vital method which actually does the conversion from integer to char[], but it's a package-private method.
So the question is how to get this method called with minimum overhead.
Following is an overview of the 3 approaches by tracing the calls to our target method, please look into the JRE source code to understand this better.
"" + intVar compiles to :new StringBuilder() => StringBuilder.append(int) => Integer.getChars(...)String.valueOf(intVar) => Integer.toString(intVar) => Integer.getChars(...) Integer.toString(intVar) => Integer.getChars(...)The first method unnecessarily creates one extra object i.e. the StringBuilder.
The second simply delegates to third method.
So you have the answer now.
PS: Various compile time and runtime optimizations come into play here. So actual performance benchmarks may say something else depending on different JVM implementations which we can't predict, so I generally prefer the approach which looks efficient by looking at the source code.