本文主要进行Ioc容器性能对比测试。
先把代码贴上,代码很容易看明白,由于Munq编译时提示没有引用,明明添加了的,还没找到原因(已经解决)。
准备基础代码:
interface IDal { void save(); } interface ILog { } class OracleDal : IDal { public void save() { //Console.WriteLine("SqlServer save."); } }
测试计时:
class Program { const long iterations = 10000; private static List<Test> ts = new List<Test> { new AutofacTest() , new WindsorTest() , new StructureMapTest(), new UnityTest(), new NinjectTest(), new MunqTest() }; static void Main(string[] args) { Console.WriteLine("Running {0} iterations", iterations); Console.WriteLine("{0,16}: {1,12} - {2,12} ", "Test Name", "Ticks", "mSec"); Console.WriteLine("-------------------------------------------------------"); ts.ForEach(c => Measure(c)); Console.Read(); } private static void Measure(Test t) { GC.Collect(); var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < iterations; i++) { t.Run(); } stopwatch.Stop(); var ticks = stopwatch.ElapsedTicks; Console.WriteLine("{0,16}: {1,12:N0} - {2,12:N2} ", t.GetType().Name, ticks, ticks * 1000 / Stopwatch.Frequency); } }
MunqTest:
using Munq; namespace IocTestDemo { class MunqTest : Test { static IocContainer container; static MunqTest() { container = new IocContainer(); container.Register<IDal, OracleDal>(); } public override void Run() { container.Resolve<IDal>().save(); } } }
StructMapTest:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using StructureMap; namespace IocTestDemo { class StructureMapTest:Test { static IContainer container; static StructureMapTest() { container = new Container(); container.Configure(x => x.Register<IDal>(new OracleDal())); } public override void Run() { container.GetInstance<IDal>().save(); } } }
结果
循环10,000次:
循环100,000次:
以上测试根据最新的组件进行测试,仅供参考。