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.

3
  • Is the question "How is it possible for two similar benchmarks to show opposite results for two different VMs running on two different platforms?" Commented 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! Commented 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. Commented Jan 13, 2021 at 21:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't think this is true for Java 9+, am I wrong?
what would be different?
I have read this, but I have never looked too deep into it, so I'd rather not make any bold claims.
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
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) stackoverflow.com/questions/50084240/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.