Literacy使用IL指令生成方法委托,性能方面,在调用次数达到一定量的时候比反射高很多
当然,用IL指令生成一个方法也是有时间消耗的,所以在只使用一次或少数几次的情况,不但不能提高性能,反而会使性能下降,所以使用场合需要自己把握
下面是在我的电脑上做的一些测试(因机器配置不同会有少许误差)
测试次数Literacy反射1016ms0ms10015ms0ms1K16ms5ms1W16ms50ms10W23ms505ms100W87ms5149ms示例代码:
static void Mai(strig[] args){ User u = ew User(); CodeTimer.Iitialize(); CodeTimer.Time("MethodIfo", 1000000, () => GetName2(u)); CodeTimer.Time("Literacy", 1000000, () => GetName(u)); CodeTimer.Time("dyamic", 1000000, () => GetName3(u));}static ObjectProperty prop;public static object GetName(object obj){ if (obj == ull) throw ew ArgumetNullExceptio("obj"); if (prop == ull) { prop = ew Literacy(obj.GetType()).Property["Name"]; if (prop == ull) throw ew NotSupportedExceptio("对象不包含Name属性"); } retur prop.GetValue(obj);}static MethodIfo getName;public static object GetName2(object obj){ if (obj == ull) throw ew ArgumetNullExceptio("obj"); if (getName == ull) { getName = obj.GetType().GetProperty("Name").GetGetMethod(); } retur getName.Ivoke(obj, ull); //缓存了反射Name属性}public static object GetName3(object obj){ if (obj == ull) throw ew ArgumetNullExceptio("obj"); retur ((dyamic)obj).Name;}
评论