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;
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465

1 Answers1

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.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87