Dependency Injection inside a loop vs via a factory – part 2

In my last post I compared calling Ninject inside a loop during object contruction vs calling Ninject once and using a factory class to return a singleton. That wasn’t an entirely fair comparison as Ninject was creating a new instance of the injected class every time, which I thought may be part of the cause of the difference in performance. So I’ve changed my test a bit so that Ninject uses a singleton as well.

Originally the Ninject kernel binding was like this:

NinjectContainer.Kernel.Bind<IAdditionProvider>().To<AdditionProvider>();

That tells Ninject to create a new instance of AdditionProvider every time. To get it to use the same instance – in effect a singleton – I changed the binding to this:

NinjectContainer.Kernel.Bind<IAdditionProvider>().ToConstant(new AdditionProvider());

I expected to see a huge performance gain, and feel like an idiot. There was a bit of a gain:

That’s roughly 8 seconds (or 12%) less then the 1m5s taken the first time around. So there’s a good gain to be had using ToConstant() to avoid creating unnecessary instances of the injected class, but still nothing like the benefits of only directly using Ninject outside of the loop.

Comments are closed.