Performance of "instanceof"
Thomas.Rodriguez at Sun.COM
Wed Jan 14 18:19:37 PST 2009
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.
On Jan 13, 2009, at 4:49 AM, Ulf Zibis wrote:
> 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