• Post Reply Bookmark Topic Watch Topic
  • New Topic

""+x versus String.valueOf(x)  RSS feed

 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been looking at the behaviour of ""+x versus String.valueOf(x) and while the first is slightly shorter and possibly easier to read, my guess is that it involves 3 String instances (one that is probably pooled) while the second would only create the one String instance.

Not a massive difference, but some of them are right in the core of our logic so I thought it was worth pursuing.
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David O'Meara:
I have been looking at the behaviour of ""+x versus String.valueOf(x) and while the first is slightly shorter and possibly easier to read, my guess is that it involves 3 String instances (one that is probably pooled) while the second would only create the one String instance.

Not a massive difference, but some of them are right in the core of our logic so I thought it was worth pursuing.

Correct me if I'm wrong, but I think it also involves a StringBuilder (implicitly), using +.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Garrett Smith:

Correct me if I'm wrong, but I think it also involves a StringBuilder (implicitly), using +.

Close, but it will probably use String.valueOf(x) instead of x.toString() to handle null values correctly, and all primitive types as well.

So yeah, new StringBuilder("").append(String.valueOf(x)).toString() is less efficient than just String.valueOf(x).
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A while ago I wandered about the same problem and did some searching around.
The conclusion was not using x + "".
Both String.valueOf(x) and Integer.toString(x) where considered equally good, while the first one is more consistent for different types and the second one is slightly more readable.
So we settled for String.valueOf(x).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!