在 Java 中使用 instanceof 的性能影响 [英] The performance impact of using instanceof in Java

查看:53
本文介绍了在 Java 中使用 instanceof 的性能影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中一种设计方法涉及大量使用 instanceof 运算符.虽然我知道 OO 设计通常会尽量避免使用 instanceof,但这是另一回事,这个问题纯粹与性能有关.我想知道是否有任何性能影响?和 == 一样快吗?

I am working on an application and one design approach involves extremely heavy use of the instanceof operator. While I know that OO design generally tries to avoid using instanceof, that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as ==?

例如,我有一个包含 10 个子类的基类.在采用基类的单个函数中,我会检查该类是否是子类的实例并执行一些例程.

For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine.

我想到的其他解决方法之一是使用type id"整数原语,并使用位掩码来表示子类的类别,然后对子类type id"进行位掩码比较" 到代表类别的常量掩码.

One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category.

instanceof 是否被 JVM 以某种方式优化为比这更快?我想坚持使用 Java,但应用程序的性能至关重要.如果以前走过这条路的人可以提供一些建议,那就太酷了.是我吹毛求疵还是专注于错误的优化?

Is instanceof somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?

推荐答案

现代 JVM/JIT 编译器已经消除了大多数传统缓慢"编译器对性能的影响.操作,包括instanceof、异常处理、反射等

Modern JVM/JIT compilers have removed the performance hit of most of the traditionally "slow" operations, including instanceof, exception handling, reflection, etc.

正如 Donald Knuth 所写,我们应该忘记小效率,比如大约 97% 的时间:过早的优化是万恶之源.";instanceof 的性能可能不会成为问题,所以不要浪费时间想出奇特的变通方法,直到您确定这是问题所在.

As Donald Knuth wrote, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." The performance of instanceof probably won't be an issue, so don't waste your time coming up with exotic workarounds until you're sure that's the problem.

这篇关于在 Java 中使用 instanceof 的性能影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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