Literacy快速反射讀寫對象屬性,字段
Literacy使用IL指令生成方法委托,性能方面,在調用次數(shù)達到一定量的時候比反射高很多
當然,用IL指令生成一個方法也是有時間消耗的,所以在只使用一次或少數(shù)幾次的情況,不但不能提高性能,反而會使性能下降,所以使用場合需要自己把握
下面是在我的電腦上做的一些測試(因機器配置不同會有少許誤差)
| 測試次數(shù) | Literacy | 反射 |
| 10 | 16ms | 0ms |
| 100 | 15ms | 0ms |
| 1K | 16ms | 5ms |
| 1W | 16ms | 50ms |
| 10W | 23ms | 505ms |
| 100W | 87ms | 5149ms |
示例代碼:
static void Main(string[] args)
{
User u = new User();
CodeTimer.Initialize();
CodeTimer.Time("MethodInfo", 1000000, () => GetName2(u));
CodeTimer.Time("Literacy", 1000000, () => GetName(u));
CodeTimer.Time("dynamic", 1000000, () => GetName3(u));
}
static ObjectProperty prop;
public static object GetName(object obj)
{
if (obj == null) throw new ArgumentNullException("obj");
if (prop == null)
{
prop = new Literacy(obj.GetType()).Property["Name"];
if (prop == null) throw new NotSupportedException("對象不包含Name屬性");
}
return prop.GetValue(obj);
}
static MethodInfo getName;
public static object GetName2(object obj)
{
if (obj == null) throw new ArgumentNullException("obj");
if (getName == null)
{
getName = obj.GetType().GetProperty("Name").GetGetMethod();
}
return getName.Invoke(obj, null); //緩存了反射Name屬性
}
public static object GetName3(object obj)
{
if (obj == null) throw new ArgumentNullException("obj");
return ((dynamic)obj).Name;
}評論
圖片
表情
