A quick post about creating string objects from other objects. Here are my two key takeaways:
(String) cast is the fastest
If you’re 100% sure that an object is – and can only be – a string, a cast is the quickest option. This answer on stackoverflow suggests that the reason for this is that casting is a feature of the JVM itself while
String.valueOf() are Java functions executed in the JVM runtime just like all Java bytecode. The JVM docs indicate that casting is part of the JVM’s instruction set.
Casting is not the same as a conversion. It’s a message to the compiler to treat an object as a different kind of object (check this answer on stackoverflow).
There is a benchmark on Cowtowncoder’s blog that suggests that casting is twice as fast as
toString(). That said – it’s still pretty darn fast. You shouldn’t use casting for the sake of performance if you’re dealing with a string object.
String.valueOf() is safer than
myObject.toString() will throw a
myObject turns out to be
null. Doing a
String myString = String.valueOf(myObject);
will not be problem if
String.valueOf() will check if the parameter is
null before doing a
myObject.toString() conversion. If
String.valueOf() function will simply return
That seems very convenient, but it will not make a big difference in your code. If you use
toString() and check for
null before that, you’ll be fine. On the other hand, with
String.valueOf() you will have to check for
null afterwards, because you want use that string reference for something (why else create it?). So you will have to check if it’s
null… I see nothing gained here – it’s a matter of taste.