Is there any runtime cost for Casting in Java?
Solution 1
Well, the compiled code probably includes the cast twice in the second case - so in theory it's doing the same work twice. However, it's very possible that a smart JIT will work out that you're doing the same cast on the same value, so it can cache the result. But it is having to do work at least once - after all, it needs to make a decision as to whether to allow the cast to succeed, or throw an exception.
As ever, you should test and profile your code if you care about the performance - but I'd personally use the first form anyway, just because it looks more readable to me.
Solution 2
Yes. Checks must be done with each cast along with the actual mechanism of casting, so casting multiple times will cost more than casting once. However, that's the type of thing that the compiler would likely optimize away. It can clearly see that input hasn't changed its type since the last cast and should be able to avoid multiple casts - or at least avoid some of the casting checks.
In any case, if you're really that worried about efficiency, I'd wonder whether Java is the language that you should be using.
Personally, I'd say to use the first one. Not only is it more readable, but it makes it easier to change the type later. You'll only have to change it in one place instead of every time that you call a function on that variable.
Solution 3
I agree with Jon's comment, do it once, but for what it's worth in the general question of "is casting expensive", from what I remember: Java 1.4 improved this noticeably with Java 5 making casts extremely inexpensive. Unless you are writing a game engine, I don't know if it's something to fret about anymore. I'd worry more about auto-boxing/unboxing and hidden object creation instead.
Solution 4
Acording to this article, there is a cost associated with casting.
Please note that the article is from 1999 and it is up to the reader to decide if the information is still trustworthy!
Ipsquiggle
"Slow burn" Japanese learner, I've been studying for about 30 minutes a day on the bus for a couple years now, my knowledge has been growing very slowly but also steadily! What fun!
Updated on June 02, 2022Comments
-
Ipsquiggle almost 2 years
Would there be any performance differences between these two chunks?
public void doSomething(Supertype input) { Subtype foo = (Subtype)input; foo.methodA(); foo.methodB(); }
vs.
public void doSomething(Supertype input) { ((Subtype)input).methodA(); ((Subtype)input).methodB(); }
Any other considerations or recommendations between these two?
-
Jon Skeet about 14 yearsDo you think there's a slight possibility that Java performance considerations may have changed in the last 10 years? :)
-
Ipsquiggle about 14 yearsI often use the second type if I am only doing one thing with the cast object. This is a simplification of a situation where several times in the method I do 'just one thing'. Effectively wondering if it's worthwhile to declare a cast reference at the beginning of the method to use throughout. (Though admittedly that's a slightly different question.)
-
Ipsquiggle about 14 yearsIt's not a big worry, just one of those nagging doubts I'd like to clear up.
-
Jonathan M Davis about 14 years@lpsquiggle That's understandable. All else being equal, it's good to code the way that's more efficient. Maintainability would likely be a bigger concern here though. But then again, the most maintainable one is also the most efficient one here, so it's a win-win.
-
Yoni about 14 years@Ipsquiggle, there is no cost of declaring the cast reference beforehand. The compiler needs to create that reference anyways, even though it is a sort of "anonymous reference".
-
Ipsquiggle about 14 yearsAccepting this answer because it has more votes, though this one and Jonathan M Davis' answer are nearly identical.
-
Riyad Kalla almost 13 yearsFYI, this is incorrect; nothing is determined at compile-time with the first example and is logically equivalent to the 2nd example: the method is accepting SuperType and attempting a cast to SubType at some point inside the method (either once or twice depending on the snippet used) -- the VM still has to evaluate the expression at runtime to see if the cast can succeed. If he wanted to use generics, then yes, some information would be established at compile-time.
-
James McMahon over 12 yearsRiyad is correct, you can test this by trying your first case code in a situation where the object can't be cast. The resulting error will happen at run time.
-
Pacerier over 12 years@JonSkeet Btw if we can confirm that the cast will absolutely not fail, is there a better "function" we can use in Java? (for example, we have the
DirectCast
in Vb for casts that don't require any form of conversion). Or is the best case really to cast once and store it in some variable (assuming readability is slightly better for the case of the multiple casts in my case). -
Jon Skeet over 12 years@Pacerier: Just the "cast once and store" is the best I know of.
-
vach about 9 yearsPeople are writing HFT software on java and you're thinking java is not suitable for performance? :)
-
Reloecc about 8 years@vach I am allways happy when I remember, how all internet was "java is dying, it's slow, worst memory management ever". And BAM! Android.