I'm writing some code that calls Field.set
and Field.get
many many thousands of times. Obviously this is very slow because of the reflection.
I want to see if I can improve performance using MethodHandle
in Java 7. So far here's what I have:
Instead of field.set(pojo, value)
, I'm doing:
private static final Map<Field, MethodHandle> setHandles = new HashMap<>();MethodHandle mh = setHandles.get(field);if (mh == null) { mh = lookup.unreflectSetter(field); setHandles.put(field, mh);}mh.invoke(pojo, value);
However, this doesn't seem to perform better than the Field.set call using reflection. Am I doing something wrong here?
I read that using invokeExact
could be faster but when I tried using that I got a java.lang.invoke.WrongMethodTypeException
.
Has anyone successfully been able to optimize repeated calls to Field.set or Field.get?