0

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.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Cole Henrich
  • 155
  • 3
  • 17
  • 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 Jan 13 '21 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 Jan 13 '21 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 Jan 13 '21 at 21:09

1 Answers1

4

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.

Sean F
  • 4,344
  • 16
  • 30
  • I don't think this is true for Java 9+, am I wrong? – Ecto Jan 13 '21 at 20:59
  • what would be different? – Sean F Jan 13 '21 at 21:00
  • I have read [this](https://www.baeldung.com/java-string-concatenation-invoke-dynamic), but I have never looked too deep into it, so I'd rather not make any bold claims. – Ecto Jan 13 '21 at 21:02
  • well it looks like there is now the opportunity to introduce new concatenation algorithms, but that change doesn't specify if a new approach has been implemented in a java release, or if it just links dynamically to the same StringBuilder approach – Sean F Jan 13 '21 at 22:50
  • as far as I can tell, dynamic implementations continue to use a StringBuilder approach in most cases, so this answer remains mostly accurate (it's just not compiler-generated code anymore) https://stackoverflow.com/questions/50084240/strategy-in-stringconcatfactory – Sean F Jan 13 '21 at 22:56