Why are annotations under Android such a performance issue (slow)?

前端 未结 4 525
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 05:56

I\'m the lead author of ORMLite which uses Java annotations on classes to build database schemas. A big startup performance problem for our package turns out to be the call

4条回答
  •  隐瞒了意图╮
    2020-12-02 05:58

    Here's a generic version of Gray's & user931366's idea:

    public class AnnotationElementsReader {
    
        private static Field elementsField;
        private static Field nameField;
        private static Method validateValueMethod;
    
        public static HashMap getElements(Annotation annotation)
                throws Exception {
            HashMap map = new HashMap();
            InvocationHandler handler = Proxy.getInvocationHandler(annotation);
            if (elementsField == null) {
                elementsField = handler.getClass().getDeclaredField("elements");
                elementsField.setAccessible(true);
            }
            Object[] annotationMembers = (Object[]) elementsField.get(handler);
            for (Object annotationMember : annotationMembers) {
                if (nameField == null) {
                    Class cl = annotationMember.getClass();
                    nameField = cl.getDeclaredField("name");
                    nameField.setAccessible(true);
                    validateValueMethod = cl.getDeclaredMethod("validateValue");
                    validateValueMethod.setAccessible(true);
                }
                String name = (String) nameField.get(annotationMember);
                Object val = validateValueMethod.invoke(annotationMember);
                map.put(name, val);
            }
            return map;
        }
    
    }
    

    I've benchmarked an annotation with 4 elements.
    Millisecond times for 10000 iterations of either getting values of all of them or calling the method above:

         Device        Default  Hack
    HTC Desire 2.3.7    11094   730
    Emulator 4.0.4      3157    528
    Galaxy Nexus 4.3    1248    392
    

    Here's how I've integrated it into DroidParts: https://github.com/yanchenko/droidparts/commit/93fd1a1d6c76c2f4abf185f92c5c59e285f8bc69.

提交回复
热议问题