C#泛型建立實例

1 class Test<T> where T : new()
2 {
3   public static T Instance()
4   {
5     return new T();
6   }
7 }

就上面這方法, 竟然比new object慢了幾十倍(在x86和x64上面表現不一), 我當時就驚呆了, 後來研究一番才發現, new T()被翻譯成System.Activator.CreateInstance(), 真的是日了狗了.spa

把代碼改爲翻譯

1 public static Fun<T> Instance = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile()

而後只比new object慢了四五倍…code

相關文章
相關標籤/搜索