Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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 ==?

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.

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.

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?

1 Answer

0 votes
by (46k points)
Modern JVM/JIC compilers have raised the performance hit of the most utmost of the traditionally "slow" operations, including instanceof, exception handling, reflection, etc.

 "We should ignore modest facilities, say about 97% of the time: untimely optimization is the root of all evil." The performance of instanceof apparently won't be an issue, so don't lose your time coming up with exotic workarounds till you're sure that's the dilemma.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)

Browse Categories

...