static void Main(string[] args) { var o = new AnObject(1); //强迫编译器JIT编译,生成方法的本地代码 //如果没有这步,后面方法的直接调用将会加入JIT编译的时间(尽管只有一点点) //使得结果不准确 o.Call(null); DirectUse(o, new object()); ReflectionUse(o, new object()); DelegateUse(o, new object()); GenericDelegateUse(); ExpressionUse(o, new object()); Console.ReadKey(); }
//直接调用 public static void DirectUse(AnObject o, object parameter) { var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < times; i++) { o.Call(parameter); } sw.Stop(); Console.WriteLine("直接调用方法: " + sw.ElapsedMilliseconds); sw.Restart(); for (int i = 0; i < times; i++) { var a = o.a; } sw.Stop(); Console.WriteLine("直接获取属性: " + sw.ElapsedMilliseconds); }