今天擴展一個Type的擴展方法New:性能
public static object New(this Type type, params object[] args) { Guard.ArgumentNull(type, "type"); return Activator.CreateInstance(type, args); }
而後想到了測試一下其性能,因此就和直接使用Activator.CreateInstance方法做一下比較:測試
public void TestCreateInstance() { Console.WriteLine(TimeWatcher.Watch(() => { for (var i = 0; i < 10000; i++) { var o = Activator.CreateInstance(typeof(TestSerializeClass1)); } })); Console.WriteLine(TimeWatcher.Watch(() => { for (var i = 0; i < 10000; i++) { var o = typeof(TestSerializeClass1).New(); } })); }
這彷佛是畫蛇添足的無用測試,卻着實使我大吃一驚!this
public static object New(this Type type, params object[] args) { Guard.ArgumentNull(type, "type"); if (args == null || args.Length == 0) { return Activator.CreateInstance(type); } return Activator.CreateInstance(type, args); }
再次測試的時間以下:spa