Which is faster obj instanceof class or obj.booleanAnyMethod()
I was asked this in an interview. Not counting the time it takes to ex开发者_开发知识库ecute the method body. Any ideas?
My answer to this question would be "I don't care". If I was having a problem with an application that I was writing and I suspected instanceof
to be the cause, then I would profile to see if it really was the cause, but I wouldn't go through rewriting large chunks of code just on a "hunch".
I'd want to profile it to quantify the difference, but I would guess instanceof
is faster.
Think about it… booleanReturnMethod()
is an instance method (if it were static, you'd already know the class), so the first step in method dispatch would be to determine what class of object it is. That's like an instanceof
right there.
But then the actual method body has to be located, and the invocation has to be set up. Even if you discount the method body itself, that preparation takes some additional time.
First, I would guess the method call, but only by a hair, since determining class instance relationship is actually fairly complicated involving not only the full class name but also the class loader that loaded it.
Second, measure and see, on the target hardware and JVM, then be prepared for the results to change with the next JVM version.
Third, who the heck cares, unless you are going to design an architecture that fundamentally depends on checking instances at a very very high rate. In any system of reasonable complexity, this is not going to even remotely be a factor... but that's just my 2 cents, and I am usually very predisposed toward giving thought to the performance of specific coding styles.
Fourth, the method call style is usually better OO than checking types, but one would have to see the system in context to be sure this is so.
I don't really understand this question... So the guy interviewing you wanted to see if you know whether an instanceof keyword would be faster than calling a random method? First of all I'd say say as it's a keyword so I'd figure that the JVM would have less problems with it than with a method you declared. But then I'd say that I don't really care since I don't really like to rely on instanceof and I really use it only when I'm forced to. I mean if I have to make a piece of code where I rely on something like "if T instanceof Z else ..." then I really take a minute or two to think whether I'm doing something wrong.
精彩评论