Java 中的 Casting 是否有任何运行时成本? [英] Is there any runtime cost for Casting in Java?

查看:22
本文介绍了Java 中的 Casting 是否有任何运行时成本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个块之间会有性能差异吗?

Would there be any performance differences between these two chunks?

public void doSomething(Supertype input)
{
    Subtype foo = (Subtype)input;
    foo.methodA();
    foo.methodB();
}

对比

public void doSomething(Supertype input)
{
    ((Subtype)input).methodA();
    ((Subtype)input).methodB();
}

这两者之间还有其他考虑或建议吗?

Any other considerations or recommendations between these two?

推荐答案

好吧,在第二种情况下,编译后的代码可能包含两次强制转换 - 所以理论上它做了两次相同的工作.但是,智能 JIT 很可能会发现您正在对相同的值执行相同的转换,因此它可以缓存结果.但它必须至少做一次工作——毕竟,它需要决定是允许强制转换成功,还是抛出异常.

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.

这篇关于Java 中的 Casting 是否有任何运行时成本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆