Recently I began to study IL, to see the origin of Odin internal source to create a Type using this approach was curious why.
First throw code examples:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class TestClass 2 { 3 public TestClass() 4 { 5 mylist = new List<int>(); 6 for(int i=0;i<100;i++) 7 { 8 mylist.Add(i); 9 } 10 } 11 12 public int x = 5; 13 public List<int> mylist; 14 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // Do Some Test 2 int needCnt = 10000; 3 var preTime = EditorApplication.timeSinceStartup; 4 for(int i=0;i<needCnt;i++) 5 { 6 TestClass t = new TestClass(); 7 } 8 var nowTime = EditorApplication.timeSinceStartup; 9 Debug.Log("通常创建的时间 " + (nowTime - preTime)); 10 11 var type = typeof(TestClass); 12 var constructor = type.GetConstructor(Type.EmptyTypes); 13 var method = new DynamicMethod(type.FullName + "_FastCreator", type, Type.EmptyTypes); 14 15 var il = method.GetILGenerator(); 16 17 il.Emit(OpCodes.Newobj, constructor); 18 il.Emit(OpCodes.Ret); 19 20 var fastCreator = (Func<TestClass>)method.CreateDelegate(typeof(Func<TestClass>)); 21 22 is PRETime = EditorApplication.timeSinceStartup; 23 is for ( int I = 0 ; I <needCnt; I ++ ) 24 { 25 var T = constructor.Invoke ( new new Object [] {}); 26 is } 27 nowtime = EditorApplication.timeSinceStartup; 28 the Debug .log ( " time and no transition Invoke constructor creates " + (nowtime - PRETime)); 29 30 PRETime = EditorApplication.timeSinceStartup; 31 is for(int i=0;i<needCnt;i++) 32 { 33 TestClass t = constructor.Invoke(new object[] {}) as TestClass; 34 } 35 nowTime = EditorApplication.timeSinceStartup; 36 Debug.Log("构造函数Invoke创建的时间 " + (nowTime - preTime)); 37 38 preTime = EditorApplication.timeSinceStartup; 39 for(int i=0;i<needCnt;i++) 40 { 41 is the TestClass T = fastCreator (); 42 is } 43 is nowtime = EditorApplication.timeSinceStartup; 44 is Debug.Log ( " Time Emit created " + (nowtime - PRETime));
Test results were as follows (run directly on a Unity):
Looks like the result is a new direct through time with the IL Emit the same time a number of levels, by the time method.Invoke slower on the double.
Personal guess Odin choose this approach to create various types of the following reasons: 1. Invoke faster time than Type 2. The only information that can not easily call the new 3 manufactured to a commission, then the next time (guess?).
After the experience more to add. . .