1

In Java there is a method that has a parameter, and this parameter is an Interface. Using such method can I do a cast to a concrete class?

How can I calculate the cost of this cast performance-wise?

Example - casting Interface to Class:

public void convertToClass(IUser iu) {          
        User u = (User) iu;
}
Dimitar
  • 4,402
  • 4
  • 31
  • 47
dev30
  • 11
  • 1
  • 7
    It's not related to performance in any way. It's a design problem. If you accept a `IUser` parameter, but then cast it to `User`, you shouldn't be accepting `IUser` as a parameter in the first place. You should be requiring a `User` parameter. – Kayaman Dec 30 '17 at 11:20
  • 1
    @Kayaman - There is a performance aspect too, though, as the compiler will have to insert a `CHECKCAST` opcode. – Oliver Charlesworth Dec 30 '17 at 11:23
  • 1
    @OliverCharlesworth sure, but that's micro level stuff. The presented code doesn't really make much sense. – Kayaman Dec 30 '17 at 11:27
  • Kayamans comment is true for the most part but the real design problem is that you need to access something from `User` at all which is not provided by the `IUser` interface. – Timothy Truckle Dec 30 '17 at 11:29
  • **Beware of premature optimization!** Never omit readability for performance considerations unless you have *proven by measurement* that this particular piece of code is a bottleneck and the "more performant" version really solves your performance problem. – Timothy Truckle Dec 30 '17 at 11:41
  • 2
    Casts should be avoided as much as possible, but not for performance reasons. You should avoid casts because casts make your code less type-safe. A cast is a way to circumvent the compiler's type checks. Kayaman's advice is important: if the method needs a `User` object, then make the parameter of type `User` instead of `IUser`. – Jesper Dec 30 '17 at 11:43

1 Answers1

4

Like said in a comment, in practice it's not a matter of performance, but of expressing your intent: if you require a specific class, you should require that, not an interface. However, often the case is that you can require an interface and then operate through that interface, omitting the cast altogether. This is also how it usually should be done. You should explore that possibility.

As to the actual question: the cast has some overhead, but it shouldn't matter in pretty much any use case. The overhead comes from checking if the cast is possible and throwing an exception if it is not. If you're interested in further discussion about the overhead of casting, you can read more about it here. If you wan't to measure the overhead, you should use methods outlined in How do I write a correct micro-benchmark in Java?

eis
  • 51,991
  • 13
  • 150
  • 199