jOOR icon indicating copy to clipboard operation
jOOR copied to clipboard

Add reflection cache

Open markzhai opened this issue 8 years ago • 5 comments

It would be slow if calling the same reflection methods from time to time, can the library provide this function?

Like https://github.com/Qihoo360/DroidPlugin/tree/master/project/Libraries/DroidPlugin/src/com/morgoo/droidplugin/reflect FieldUtils.java:

public class FieldUtils {

    private static Map<String, Field> sFieldCache = new HashMap<String, Field>();
    ...
    private static Field getField(Class<?> cls, String fieldName, final boolean forceAccess) {
        Validate.isTrue(cls != null, "The class must not be null");
        Validate.isTrue(!TextUtils.isEmpty(fieldName), "The field name must not be blank/empty");

        String key = getKey(cls, fieldName);
        Field cachedField;
        synchronized (sFieldCache) {
            cachedField = sFieldCache.get(key);
        }
        if (cachedField != null) {
            if (forceAccess && !cachedField.isAccessible()) {
                cachedField.setAccessible(true);
            }
            return cachedField;
        }
        ...
    }
    ...
}

markzhai avatar Mar 03 '16 09:03 markzhai

Have you benchmarked this implementation via JMH? I wouldn't be surprised if the synchronisation + hashmap access is slower than the current implementation!

lukaseder avatar Mar 03 '16 22:03 lukaseder

I'm debating a PR to add this capability as I agree with the @markzhai that it would be good to add because I personally built something similar to this in our own application because we found Class and field level caching to be beneficial, especially on certain JVM's.

The only difference between my implementation and the suggested one is that we used a ConcurrentHashMap for both the classes and the separate one for the set of fields.

rdifrango avatar Jul 22 '16 02:07 rdifrango

@rdifrango Quite possibly, this might speed up things - but I'd like to be sure about it.

Another caveat that has not been discussed yet is OSGi or other scenarios where caching reflection information will be detrimental. It should certainly be possible to turn off caching, which makes me wonder if we perhaps shouldn't re-design jOOR and avoid the static API... That way, an SPI could be created which allows for injecting different caching strategies.

lukaseder avatar Jul 22 '16 05:07 lukaseder

@lukaseder We aren't in an OSGi environment so it's a good call that it might be detrimental there. I can tell you though in traditional environments the caching definitely is/was beneficial.

I do like the idea of a re-design of the API to avoid the static's allowing for a caching strategy to be customized by users of the library.

rdifrango avatar Jul 29 '16 15:07 rdifrango

Will think about it...

lukaseder avatar Aug 02 '16 05:08 lukaseder