0

Is there a reason to prefer either string concatenation or invoking toString when converting objects to string representations?

Does string concatenation cause the object's toString method to be invoked?

String s;
Properties p = System.getProperties();
s = p.toString();
s = "" + p;
12
  • Basically, concatenation involves an extra StringBuilder. Commented Oct 29, 2015 at 2:53
  • Slightly related: stackoverflow.com/questions/47605/… Commented Oct 29, 2015 at 2:54
  • @SotiriosDelimanolis, is that a reason to prefer one over the other? It's not a duplicate question. Commented Oct 29, 2015 at 2:55
  • p.toString() doesn't involve a new object. "" + p involves a new object. (Though I would imagine the "" could be removed by a smart compiler.) After that, it's all opinion, what looks better. Commented Oct 29, 2015 at 2:56
  • so your answer is "there's no reason to prefer one over the other"? Commented Oct 29, 2015 at 2:57

1 Answer 1

2

p.toString() is better.

When you say s=""+p, the compiler makes something like this:

{
    StringBuilder sb = new StringBuilder();
    sb.append("").append(p.toString());
    s=sb.toString();
}

So, yes, ""+p does mean that p.toString() gets called, but it also adds a lot of extra work.

The best thing that can happen is that the compiler recognizes that it's the same as p.toString() and just calls that instead, but you shouldn't count on that.

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

1 Comment

I think it does String.valueOf(p), not p.toString() though the former calls the latter when p != null.

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.