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.
-
Is the question "How is it possible for two similar benchmarks to show opposite results for two different VMs running on two different platforms?"that other guy– that other guy2021-01-13 20:50:24 +00:00Commented Jan 13, 2021 at 20:50
-
@thatotherguy it's because our benchmarks were made differently, and maybe also to do with setText vs. plain conversion in the other question. But if there is some other reason, sure, let us know!Cole Henrich– Cole Henrich2021-01-13 20:57:54 +00:00Commented Jan 13, 2021 at 20:57
-
It’s even bet that it’s sometimes faster, and sometimes slower, depending on what version of the JDK you are using. But it’s just use either String.valueOf() or the static Integer.toString() in this case.Axel– Axel2021-01-13 21:09:44 +00:00Commented Jan 13, 2021 at 21:09
1 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.