Kazed

Pragmatic software development

  • Increase font size
  • Default font size
  • Decrease font size
Home

Tags: android | java | testing


I am experimenting with a simple form of dependency injection that uses reflection and annotations. I was wondering what the performance of this solution is, since reflection once was rumored to be very slow.

First I measured the speed of setting up a HashMap with the service bindings; this consists of a simple map.put() operation:

public void bind(Class interfaceClass, Class implementationClass) {
    binding.put(interfaceClass, implementationClass);
}

This turns out to be very fast: this takes 0.0002 milliseconds.

 I also provide a way of binding a service that checks the existence of an annotation:

public void bind(Class implementationClass) {
    Component component = implementationClass.getAnnotation(Component.class);
    binding.put(component.value(), implementationClass);
}

 Here, the additional annotation lookup makes this a bit slower: 0.0005 milliseconds.

 The injection uses reflection to lookup the setter methods and is a bit more work:

public void inject(Object target) {
    Class targetClass = target.getClass();
    Method[] methods = targetClass.getMethods();
    for (Method method : methods) {
        if (method.getName().startsWith("set")) {
            // method is a setter, check if method has "@Autowired" annotation
            Autowired inject = method.getAnnotation(Autowired.class);
            if (inject != null) {
                // method has annotation
                findParametersAndInvoke(target, method);
            }
        }
    }
}

This takes about 0.030 milliseconds.

To conclude these very simple benchmarks, which I have done in a for loop a few thousand times to get measurable results which may or may not be realistic, setting up the application context with a HashMap is very fast and injecting a dependency into an object less fast. I think that a typical application would not use injection into an object less often, so dependency injection should produce only minimal overhead.



Add this page to your favorite Social Bookmarking websites
Reddit! Del.icio.us! Mixx! Free and Open Source Software News Google! Live! Facebook! StumbleUpon! Yahoo! Free Joomla PHP extensions, software, information and tutorials.