William Brogden wrote:A cast is always going to be faster than a method call.
Well, at least, if you're working in a naive environment. In
Java, casts have to pass security constraints, and method calls can be optimized . And the net result may every well be either the exact same code, or even more efficient code on the method call (if the compiler decides it can bypass the security checks for a statically-defined type). So YMMV, depending on run environment and JVM.
So ALWAYS benchmark if it matters. And if it isn't a case where some sort of horrendous performance bottleneck has been detected, save your energy for higher-level optimizations where you'll get more performance with less effort.
The
main difference, in fact, is that string.valueOf() can throw a NullPointerException, so the two code samples are not functionally equivalent!
The secret of how to be miserable is to constantly expect things are going to happen the way that they are "supposed" to happen.
You can have faith, which carries the understanding that you may be disappointed. Then there's being a willfully-blind idiot, which virtually guarantees it.