简体   繁体   English

从接口到实现类的转换的性能开销

[英]Performance overhead of casting from interface to implementation class

Suppose I have an interface Vehicle and implementation Car . 假设我有一个接口Vehicle和实现Car The class Car has a method called getNumberCylinders() that is not part of the Vehicle interface. Car类具有一个名为getNumberCylinders()的方法,该方法不属于Vehicle接口。 Thus in my code I need to cast a Vehicle instance to class Car in order to call this method. 因此,在我的代码中,我需要将Vehicle实例强制转换为Car类,以调用此方法。

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. 在这种情况下,是的,因为对象可能不是Car,所以Java必须进行运行时检查,这就是抛出ClassCastExceptions的方式。 JVM Specification #2.6.8. JVM规范#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. 尽管Java规范本身不保证它将是0纳秒的操作,但是由于强制转换操作,没有关于性能开销的明显报告。 In my application, I'll worry more on the unnecessary database hits and object creation rather than just type casting. 在我的应用程序中,我将更多地担心不必要的数据库命中和对象创建,而不仅仅是类型转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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