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

查看:3088
本文介绍了在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 / JIC编译器已经取消了大多数传统上慢的操作,包括instanceof,异常处理,反射等。

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

正如唐纳德克努特写的那样,我们应该忘记小的效率,比如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天全站免登陆