Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complexity of instanceof operator java

I was wondering how computationally expensive is using instanceof operator in java and wanted to know if there are any better alternatives available

like image 456
Chander Shivdasani Avatar asked Oct 25 '11 21:10

Chander Shivdasani


People also ask

Is Instanceof slow in java?

Instanceof is very fast. It boils down to a bytecode that is used for class reference comparison.

What is the Instanceof operator in java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. Its syntax is. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

What can I use instead of Instanceof in java?

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".

Should we use Instanceof in java?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.


1 Answers

The alternative is to avoid using instanceof and design your classes properly (in OO sense).

As the instanceof operator has a corresponding "instanceof" byte code instruction, there probably won't be a more performant approach; but this may also depend on how the actual JVM optimizes.

like image 130
jeha Avatar answered Sep 23 '22 13:09

jeha