Java statement instance complexity

I was wondering how computationally expensive it is to use the instanceof operator in java and wanted to find out if there are any better alternatives available

+6
source share
4 answers

An alternative is to avoid using instanceof and correctly create classes (in the sense of OO).

Since the instanceof operator has the corresponding instanceof "bytecode command, there probably won't be a more efficient approach; but it may also depend on how the actual JVM is optimized.

+9
source

instanceof pretty damn fast. However, this is usually a symptom of a poorly designed design.

It will have the same performance as (successful), as it does the same. Indeed, the task is roughly equivalent to calling the "virtual" method.

In normal implementations: for classes, it's just a matter of getting the runtime class and looking at a fixed offset to check for the superclass (as long as you don't have an inheritance chain of more than eight classes for HotSpot). Interfaces are a bit more complex, but usually have the last two cases used for any particular cached runtime class. So also fast.

+7
source

If you want to check if an object is an instance of a particular class (but not extends or implements ), then comparing classes with == will be faster:

 o.getClass() == YourClass.class 

Otherwise, since the instanceof keyword was created for this particular purpose, I don’t see how you could ever do better.

+2
source

I assume that you really profiled your code and found that your use of instanceof is a non-trivial performance hit? If not, you will almost certainly solve a problem that is not worth your time to resolve.

If all you do is code:

 if ( something instanceof MyClass ) { MyClass mySomething = (MyClass) something; //... } else { //exceptional case } 

Then first you can try throwing and letting ClassCastException be your "exceptional case":

 try { MyClass mySomething = (MyClass) something; } catch (ClassCastException cce) { //exceptional case } 

Now, although it may be premature optimization, it would be premature to rethink your design. The danger of using instanceof is a designer smell. In general, you should use generics and polymorphism in ways that reduce the number of times you would use instanceof (and indeed casting) to (almost) zero.

  • If, depending on the type of object, different code is to be executed, consider making this code a method of an instance of the object and have different types corresponding to the interface.

  • If you find that you β€œknow” that the object is of a certain type, but you took some step that made the compiler lose this fact (for example, you put it in a raw List ), this may be a candidate for generation.

+2
source

Source: https://habr.com/ru/post/900084/


All Articles