34

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?

Glen
  • 21,816
  • 3
  • 61
  • 76
Ipsquiggle
  • 1,814
  • 1
  • 15
  • 25

5 Answers5

30

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I 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 Jan 29 '10 at 21:32
  • 2
    @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". – Yoni Jan 29 '10 at 21:41
  • Accepting this answer because it has more votes, though this one and Jonathan M Davis' answer are nearly identical. – Ipsquiggle Jan 29 '10 at 22:34
  • @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). – Pacerier Nov 17 '11 at 13:03
  • 1
    @Pacerier: Just the "cast once and store" is the best I know of. – Jon Skeet Nov 17 '11 at 13:07
8

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.

Jonathan M Davis
  • 37,181
  • 17
  • 72
  • 102
  • 2
    It's not a big worry, just one of those nagging doubts I'd like to clear up. – Ipsquiggle Jan 29 '10 at 21:34
  • @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. – Jonathan M Davis Jan 29 '10 at 21:40
  • People are writing HFT software on java and you're thinking java is not suitable for performance? :) – vach Apr 22 '15 at 13:24
  • @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. – Reloecc Feb 06 '16 at 00:05
2

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.

Riyad Kalla
  • 10,604
  • 7
  • 53
  • 56
1

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!

Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
Oso
  • 528
  • 4
  • 18
  • 22
    Do you think there's a slight possibility that Java performance considerations may have changed in the last 10 years? :) – Jon Skeet Jan 29 '10 at 21:28
-4

In the first case :

Subtype foo = (Subtype)input;

it is determined at compile time, so no cost at runtime.

In the second case :

((Subtype)input).methodA();

it is determined at run time because compiler will not know. The jvm has to check if it can converted to a reference of Subtype and if not throw ClassCastException etc. So there will be some cost.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 3
    FYI, 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. – Riyad Kalla May 12 '11 at 15:48
  • 3
    Riyad 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. – James McMahon Oct 11 '11 at 18:44