I was wondering how computationally expensive is using instanceof operator in java and wanted to know if there are any better alternatives available
Instanceof is very fast. It boils down to a bytecode that is used for class reference comparison.
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 .
Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With