简体   繁体   中英

Performance overhead of casting from interface to implementation class

Suppose I have an interface Vehicle and implementation Car . The class Car has a method called getNumberCylinders() that is not part of the Vehicle interface. Thus in my code I need to cast a Vehicle instance to class Car in order to call this method.

Does such a cast incur a performance overhead, versus the alternative of including this method into the interface and calling that method directly without the cast?

Does such a cast incur a performance overhead, versus the alternative of including this method into the interface and calling that method directly without the cast?

In this case, yes, because the object mightn't be a Car, so Java has to do a runtime check, which is how ClassCastExceptions can get thrown. JVM Specification #2.6.8.

If you have to do this kind of thing you're usually doing something wrong at the design phase. I would reconsider your object model.

If you think all vehicles should have 'number of cylinders', then it's good to add that method to the Vehicle interface. Otherwise, casting is totally fine. At runtime, casting doesn't modify your object at all. Casting has more to do with compilation check. There is no obvious report on performance overhead due to casting operation, although Java specification itself does not guarantee it will be 0 nanosecond operation. In my application, I'll worry more on the unnecessary database hits and object creation rather than just type casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM