Performance of "instanceof"
Ulf Zibis
Ulf.Zibis at gmx.de
Thu Jan 15 03:21:41 PST 2009
Thanks Tom,
I was asking because of my RFE 8 in
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6790402.
So I can be sure, that my proposed shortcut is much faster than the
saved HashMap lookup, and hopefully HotSpot remembers the result of
"instanceof", so following cast to String could be skipped.
I was in doubt, how the right part of "instanceof" would retrieve a
reference pointer to the Class class from the given class name. So as I
understand you right, MyClass.klass is static final available from bytecode.
-Ulf
Am 15.01.2009 03:19, Tom Rodriguez schrieb:
> instanceof is the fastest way of asking the question it's designed to
> ask. The three code patterns below aren't necessarily asking the same
> question though. If MyClass has no subclasses then instanceof
> devolves into obj.klass == MyClass.klass, so a load and pointer
> compare against an embedded constant. If it has subclasses then our
> fast subtype check should trigger which is roughly a couple loads and
> a compare, unless the hierarchy is deep or MyClass is an interface.
> obj.getClass() == mypackage.MyClass.class will produce something
> relatively efficient. It should be something like
> obj.klass.klass_mirror == MyClass.
> obj.name().equals(objOfMyClass.name()) would be better with == which
> you could rely on if you either explicitly interned the name or used a
> constant string for the name so those are automatically interned for
> you. If you have to call .equals it's probably the worst. All of
> this should be true for client and server, with server producing at
> least slightly tighter code and maybe an extra trick or two.
>
> tom
>
> On Jan 13, 2009, at 4:49 AM, Ulf Zibis wrote:
>
>> Hi,
>>
>> I'm just interested, how "instanceof" works behind the scenes. Does
>> it simply string-compare the names of the classes, and in fail, do
>> the same with the super class in loop, or is there some
>> sophisticated algorithm.
>>
>> I'm asking, because I want to know, which is faster:
>> - obj instanceof mypackage.MyClass
>> - obj.getClass() == mypackage.MyClass.class
>> - obj.name().equals(objOfMyClass.name()) (assuming, each MyClass
>> has it's own name, as it is the fact for Charset subclasses.)
>>
>> - Ulf
>>
>>
>
>
More information about the hotspot-dev
mailing list