aspose file tools
The moose likes Java in General and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark """+x versus String.valueOf(x)" Watch """+x versus String.valueOf(x)" New topic
Author

""+x versus String.valueOf(x)

David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

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

Joined: Jun 27, 2002
Posts: 401
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 +.


comp.lang.javascript FAQ: http://jibbering.com/faq/
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19214

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).


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
bart zagers
Ranch Hand

Joined: Feb 05, 2003
Posts: 234
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).
 
jQuery in Action, 2nd edition
 
subject: ""+x versus String.valueOf(x)
 
Similar Threads
decimal to binary number converter
convert int ,double to string
importance of String.valueOf(Object)
doubt in String
Why Overloading..?