有什么方法可以进一步优化Java反射方法调用? [英] Any way to further optimize Java reflective method invocation?

查看:194
本文介绍了有什么方法可以进一步优化Java反射方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何额外的优化我可以实现以提高Java中反射调用的速度。并不是说性能太高,但是在考虑我正在编写的库中的某些代码时,我得到了一些想法在某个地方实现紧密循环。

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)

基本操作是

return method.invoke(targetObject, arguments);

作为性能优化,我使用目标对象的类,方法名称和签名(其代码可能会有一些改进)但除此之外,还有什么我可以做的吗?我听说过一些早期的 InvokeDynamic 实现的参考听起来很有希望,但我只是假设它们可能还不适用,并且我打算使用自己的字节代码操作,因为我希望保持实用程序简单(但很快)。

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).

干杯。

推荐答案

以下评论与Sun的实现有关,特别是OpenJDK 6.您的里程可能因其他Java平台实现而异。

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

java.lang.Class 自己进行一些缓存,因此实​​现自己的缓存可能无法改善。使用和不使用手动缓存进行计时测试。

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.

实际的调用机制也进行了优化。使用JNI调用反射方法的前15次运行(默认情况下);之后,生成字节码并调用反射方法将直接在Java代码中调用该方法执行相同的操作。

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.

这篇关于有什么方法可以进一步优化Java反射方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆