Why is String.valueOf faster than String Concatenation for converting an Integer to a String?



This is the converse of the problem “Why is String concatenation faster than String.valueOf for converting an Integer to a String?”. It is not a duplicate. Rather, it stems from this answer with benchmarks asserting that t.setText(String.valueOf(number)) is faster than t.setText(""+number), and ChristianB’s question as to why that is.

Answer

String addition results in the compiler creating a StringBuilder instance, followed by append calls for each added element, followed by a call to StringBuilder.toString() to create the resulting concatenated String instance.

So, ""+number creates a StringBuilder, appends a number using the same conversion as String.valueOf, and then creates a String instance from the StringBuilder with StringBuilder.toString.

String.valueOf(number) avoids the StringBuilder, just using the value from String.valueOf.

The answer might not be the same when the compiler can avoid all of this, if it can discern the final String result because the elements appended are all constants. In that case, the compiler just puts the final String into the compiled code.



Source: stackoverflow