Reputation: 304444
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;
Upvotes: 0
Views: 2185
Reputation: 59174
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.
Upvotes: 2