Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

performance - Any way to further optimize Java reflective method invocation?

I am wondering if there are any additional optimizations I can implement to improve the speed of reflective invocations in Java. Not that the performance is prohibitive, but I get the willies when thinking about some piece of code in a library I am writing being implemented in a tight loop somewhere.

Consider a utility method to invoke reflectively:

public static Object invoke(Object targetObject, String methodName, Object[] arguments, Class<?>[] signature)

The basic operation is

return method.invoke(targetObject, arguments);

As a performance optimization, I cache the method using a hash of the target object's class, method name and signature (the code of which might use some improvement) but beyond that, is there anything else I can do ? I have heard references to some early implementations of InvokeDynamic that sound promising, but I just assumed that they were probably not applicable yet, and I discounted my own byte code manipulation as I would like to keep the utility simple (but fast).

Cheers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The comments below relate to Sun's implementation, in particular OpenJDK 6. Your mileage may vary with other Java platform implementations.

java.lang.Class does some caching itself, so implementing your own cache may not improve things very much. Do timing tests with and without manual caching.

The actual invocation mechanism is optimised too. The first 15 runs (by default) of your reflected method is called using JNI; after that, bytecode is generated and calling that reflected method would perform identically to calling that method directly in Java code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...