Ninject performance

This was somewhat unexpected to me.

Just ran a test on how long it takes Ninject to instantiate 100.000 objects, and it took over a 1000x longer than making those objects using constructor (2269 ms  vs 2 ms).  If I’m asking Ninject to return a singletone, it drops down to about 1200 ms.

Yeah, it’s a lot of instances, so it’s not likely to make noticeable difference in real applications, but it’s something worth keeping in mind.  When working on a high-volume web site, this can be noticeable.

Here’s the code I used to test, just in case:

 

class NinjectPerfTest
    {
        Ninject.IKernel kernel = null;
 
        public NinjectPerfTest()
        {
            this.InitNinject();
        }
 
        private void InitNinject()
        {
            this.kernel = new Ninject.StandardKernel(new NinjectModule());
        }
 
        public void Test()
        {
            int count = 100000;
 
            DateTime start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                IWorker w = this.kernel.Get<IWorker>();
            }
            Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds + " ms with ninject");
 
            start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                IWorker w = new Worker();
            }
            Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds + " ms with constructor");
        }
 
        interface IWorker
        {
            void DoWork();
        }
 
        class Worker : IWorker
        {
            public void DoWork()
            {
                Console.WriteLine("Working hard");
            }
        }
 
        private class NinjectModule : Ninject.Modules.NinjectModule
        {
            public override void Load()
            {
                this.Bind<IWorker>().To<Worker>().InSingletonScope();
            }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *