Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any runtime cost for Casting in Java?

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?

like image 424
Ipsquiggle Avatar asked Jan 29 '10 21:01

Ipsquiggle


3 Answers

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.

like image 132
Jon Skeet Avatar answered Nov 20 '22 21:11

Jon Skeet


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.

like image 36
Jonathan M Davis Avatar answered Nov 20 '22 22:11

Jonathan M Davis


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.

like image 2
Riyad Kalla Avatar answered Nov 20 '22 20:11

Riyad Kalla