calling methods using reflection

Im wondering what kind of degrade in performance I should expect when I call methods using reflection (using an Method[]) compared to calling methods on objects the regular way.

Im not too familiar with how current (and old) JVM’s handle this kind of reflection, is there even a difference when I cache my to be called methods in this array upon initialisation of my app?

Thanks,

Thijs

It’s pretty fast, much faster than it used to be, but nowhere near as fast as the JITted code Hotspot produces for method calls. Run a little benchmark to find out.

Cas :slight_smile:

Are you sure you really need this?

Casting over to some interface is good enough in most cases.

If you need it, calling through a Method is not too bad.

Lookign that method up costs significantly more so cache Method references if at all possible.

btw. reflection was improved in 1.4, Sun’s jvms prior 1.4 may show poor reflection performance.
But in general its pretty fast if you cache the method-objects.

lg Clemens

[quote]It’s pretty fast, much faster than it used to be, but nowhere near as fast as the JITted code Hotspot produces for method calls. Run a little benchmark to find out.
[/quote]
Yeah I know, im lazy :wink:
I’ll dig up a profiler to do some tetss…

[quote]Are you sure you really need this?
Casting over to some interface is good enough in most cases.
[/quote]
Unfortunatly I need it in this case… I need to be able to call getters / setters for attributes marked as transient without knowing anything about the class structure. I crawl through the specified class and for each transient field I lookup the getter / setter and reference them in a Method[].

if I cache the methods in a HashMap<String, Method>, it’s 40% slower than using getMethod, so sticking with getMethod is definitely the better solution.

but, during my tests, this line
getClass().getMethod("__" + input.sval, new Class[] { HashMap.class }).invoke(this, new Object[] { data } );
several times actually performed better than this line, even if only by a small margin (10%)
((AbstractInstance) caller).__out(data);

huh, wacky.

This is hardly possible, maybe you’ve some other effects? microbenchmarks?
Since getMethod would do in the best case exactly the same, just look into a HashMap wether the method-object has already looked up - however since its thread-safe there would be even locking-overheads (even if uncontended), there is almost no chance for getMethod beeing faster.

lg Clemens

LH is right that makes no sense.

I’d suggest you profile and see what is really going on,

funny, it’s now indeed a good bit faster when cached. I could have sworn it wasn’t earlier ???

well if your caching logic was messed up such that you always had a cache miss, that would make it take longer then assuming the miss all the time which is what not caching at all is equivalent to.

Thats my “most likely scenario.”

may be. oh well, works fine & fast now :wink: