If I'm looping through an Object array, and each item is non-null, and
contains a String, is it faster to call toString() on each object, or
cast each object to String?
[Assuming there's some valid reason for not using a String[] instead of an
Object[]]
Simple answer: use the cast regardless of whether it's faster -- that way the
code will show what you mean, and also will fail quickly if it should turn out
that your presumption that the array contains only Strings is wrong. (Since
all objects have a toString() method, any "wrong" object will simple return the
wrong string rather than triggering an invalid cast exception).
More complex answer: It's an interesting question; if the JITer is able to
function as I believe it should (implementation dependent, of course), then
there's a reasonable chance that the cast would be compiled into a class-test +
(never taken) branch, whereas the toString() would end up being inlined at the
call site, and so would /also/ end up being a class-test + (never taken)
branch. (The class test because it would need to include code to check that
its assumption that the Object was going to turn out to be a String was
correct). Maybe I'll run a test or two later -- it may give some extra insight
into how the currrent crop of JITers are working.
Of course, it'd be stupid to code using toString() just because "it's
faster" -- even if it was, which I doubt -- except in truely /extraordinary/
circumstances. It's just not going to make much difference unless you call it
many, many, millions of times. And the hit to the code clarity is so severe
that even if it made a fairly big difference, then it'd /still/ be a bad idea.
(Especially when you have the alternative of using a String[] and thus avoiding
all the difficulties, anyway.)
-- chris