6

I have a colleague here in my project, who is deeply against the use of instanceof operator, because it "generates a lot of overhead", what is the reason for that? Is it true?

Is there another way to check the type of the Object instead of using it?

Because I find it very useful in some occasions.

Dimitar
  • 4,402
  • 4
  • 31
  • 47
Cristiano Fontes
  • 4,920
  • 6
  • 43
  • 76
  • 1
    I highly doubt it, since it is a keyword the compiler can often make static inferences about the type, and even if it can't it only has to read from a table somewhere of loaded classes to see if the current class is a subclass. – gub Feb 11 '11 at 19:55

5 Answers5

15

It does generate some overhead, combined with the subsequent casting. With recent version of Java the overhead has decreased. But anyway that's microoptimization - i.e. you should not worry about it in the general case.

The real argument against instanceof is that in many cases there are better OOP ways to achieve the desired behaviour.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • +1 for the real reason why instanceof is to be carefully thought through before use. I see lots of code where a big set of if instanceof statements should have been implemented using OO paradigms. – Kevin Day Feb 12 '11 at 05:18
  • @Bozho,Could you provide an alternate way instead of using instanceof which could be used in reducing the overhead ? – Deepak Feb 12 '11 at 13:57
  • @Deepak - polymorphism. The Visitor pattern sometimes. – Bozho Feb 12 '11 at 14:03
  • @Bozho,Any working example where you can show that indeed instanceOf has generated overhead..how do i simulate it against polymorphic behaviour – Deepak Feb 12 '11 at 14:16
  • @Bozho, actually if it's about pure overhead (and I do not recommend to anyone), if having more than 2 target classes the polymorphism can generate more overhead than instanceof. Further read: http://www.azulsystems.com/blog/cliff-click/2010-04-08-inline-caches-and-call-site-optimization – bestsss Feb 12 '11 at 14:59
  • 1
    @to anyone, do not think of such optimizations, the compilers are very decent at optimizing your code, do not write micro-benchmarks to test unless you are perfectly sure you understand why kind of optimzation the micro-benchmark might 'suffer'. – bestsss Feb 12 '11 at 15:03
  • leave the "better ways" to the developer. if "instanceof" is wrong, then "pattern matching" is wrong as well. – RamPrakash Jun 19 '23 at 16:46
3

It may or may NOT generate any overhead if the compiler can prove the instance. Even if the compiler can not prove the target immediately the overhead is very little. A few cpu clocks (esp. if instanceof jump is properly predicted).

Following casts after instanceof are usually free.

(note: by the compiler I mean the JIT one)

bestsss
  • 11,796
  • 3
  • 53
  • 63
  • :) got more rep. than I can use, so people can fix typos, errors if they please so. I tend to post under community wiki unless I forget. Btw, iirc, an `instanceof` can be as cheap as a single CPU clock for classes w/o subclasses (Long/Double/String/URL and the like) – bestsss Feb 11 '11 at 21:03
  • people can still edit your posts. So feel free to post regular answers ;) – Bozho Feb 11 '11 at 21:40
  • nay, you need quite high rep. to do so and few would dare, either way. rep is overrated :) – bestsss Feb 11 '11 at 21:41
  • you can suggest an edit regardless of the rep. – Bozho Feb 11 '11 at 23:07
2

There is no serious overhead. It's almost certainly cheaper than a home-grown getType()-style solution. Casting, while not free, is also very cheap.

As noted by Bozho it can be indicative of a flawed design, but in some situations it is the most pragmatic choice and so shouldn't be disregarded out of hand.

ryanm
  • 2,979
  • 18
  • 22
2

The main issue is that it generates code smell. If you use polymorphism instead this is a better design approach. The performance cost can be around 10 to 100 nano-seconds depending on the complexity of the call and how many implementing method you call from that line of code.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • How did you calculated the 10 nanosecond overhead? Is there another more known operation taking about the same time? – Louis CAD Mar 02 '16 at 16:26
  • @LouisCAD it is an estimated average. Note: this will depend on many factors so it could me much more. – Peter Lawrey Mar 02 '16 at 20:08
  • 1
    @PeterLawrey, So what do you think of "pattern matching" then? code smell? What is your suggestion for visitor pattern impl. – RamPrakash Jun 19 '23 at 22:09
  • @RamPrakash the best pattern is polymorphism, if you can change the classes involved to use it. However, if the classes already exist and you can't or shouldn't change them or it would involve adding a method that you wouldn't want to be part of the public API, instanceof could be the workaround. – Peter Lawrey Jun 21 '23 at 08:45
2

Actually, instanceof returning true and a cast to this type succeeding are not totally equivalent - the latter may succeed when the former returns false. So, even when there is something like this,

String s = someMethodReturningString();
Object o = s;
if (o instanceof String) {
   ...
}

the compiler has to generate at least a check o != null here.

In practice, it is neglectable, though.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • not to go into an argument but how did you assign integer to a string and if the method doesn't return null (ever) instanceof is a dead code. usually null checks are 1cpu clock, btw – bestsss Feb 12 '11 at 17:22
  • @bestsss: Ah, I first wrote the example with Integer, and then changed to object to get not into the wrapping/unwrapping-hassle. Thanks for pointing out, I'll correct this. – Paŭlo Ebermann Feb 12 '11 at 18:46
  • if the JIT can inline the code (not some multi-target virtual code) and if the end result is never null the `(o instanceof String)` will be omitted, I tried to explain it: the only operation ppl should really consider in terms of performance is accessing memory, the rest is well optimized. – bestsss Feb 12 '11 at 20:18