Poor Performance Obtaining a Singleton

Oct 19, 2010 at 9:20 AM
Edited Oct 19, 2010 at 9:20 AM

Hello,

I have this example, where I'm trying to compare the speed of allocating 100 objects manually (new) to that of resolving a single instance (ContainerControlled) via Unity:

 

UnityContainer unity = new UnityContainer(); unity.LoadConfiguration();
Stopwatch watch = new Stopwatch();
watch.Start();

for (Int32 i = 0; i < 100; ++i) { ISomeType obj = new SomeType(); obj.DoSomething(); }

Int64 time1 = watch.ElapsedMilliseconds;

watch.Restart();

for (Int32 i = 0; i < 100; ++i) { ISomeType obj = unity.Resolve<ISomeType>(); obj.DoSomething(); }

Int64 time2 = watch.ElapsedMilliseconds;

watch.Stop();

Console.WriteLine("{0} - {1}", time1, time2);

unity.Dispose();

 

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"

<container>

 <register type="ConsoleIoC.ISomeType, ConsoleIoC" mapTo="ConsoleIoC.SomeType, ConsoleIoC">

        <lifetime type="singleton"/>

</register>

</container>

</unity>

 

The problem is that the singleton version is about 9-10 times slower! Is this normal?

Thanks,

RP

Feb 7, 2011 at 11:20 PM

Yes, there's an overhead calling Resolve on a container.