Thanks Will.
The code you provided was very helpful making me understand the difference.
now i can make my decision based on that.
this comparison is going to be used at a very low lever where it will be
repeated a huge number of times, and such a difference in bahavior will make
a difference in the performace of the application.
i definately need the direct class comparison using the == operator.
I'm glad I could help, but note the quoted bit I left in.
If you downcast a variable, you will be incurring the same cost as the
instanceof operator, simply because the run time system HAS to essentially
do the same thing (which is why you get an exception during the casting
operation, rather than when trying to act upon a casted object, like in
Smalltalk).
Now arguably:
if (o instanceof SomeClass) {
SomeClass x = (SomeClass)o;
....
}
is "slower" than:
if (o.getClass() == SomeClass.class) {
SomeClass x = (SomeClass)o;
....
}
But if you are SO concerned with the price of the instanceof test, I would
suggest you forego the classes entirely and work with some scary static
structure that never has a class cast or test anywhere near your main inner
loop.
You can try:
Method someClassMethod = getMethodFromSomeClass();
Object emptyParamList = new Object[0];
if (o.getClass() == SomeClass.class) {
someClassMethod.invoke(o, emptyParamList);
}
That will save you the cast, at the expense of building the parameterlist.
But then you may lose any benefit that the HotSpot JIT may give direct
method calls.
The point being that there are a lot of hidden costs in Java, and if you're
worried about something like instanceof, and feel that it stands out for
optimization, I think you're going to find a LOT of places that also incur
costs.
And, of course, you're going to benchmark this to see what really matters.
Regards,
Will Hartung
(
[email protected])