I have always believed in the "Low Reflection Efficiency" Statement circulating on the Internet. This is a dynamic and static difference, however, how much reflection affects Programs have never been tested. Today, we have conducted a test in a realistic manner.
Using system; using system. diagnostics; using system. reflection; Class program4 {static void main () {Assembly = assembly. getexecutingassembly (); Module [] modules = assembly. getmodules (false); Type type = assembly. getType ("threadclass"); methodinfo MI = type. getmethod ("test"); stopwatch watch = new stopwatch (); watch. start (); For (INT I = 0; I <10000; I ++) {threadclass. test ();} watch. stop (); console. writeline (watch. elapsedticks); watch. restart (); For (INT I = 0; I <10000; I ++) {mi. invoke (null, null);} watch. stop (); console. writeline (watch. elapsedticks); console. read () ;}} class threadclass {public static void test () {// nothing }}
Do not do anything in the method to be called. This will better display the "Pure call" gap and print the result:
772
9345
From the result, less than 10000 ticks (10000 ticks is equivalent to 1 millisecond), which indicates that the difference between pure calls is that more than 10 thousand times will have a millisecond error, which is small enough, if you do something in the called method, the difference is negligible.
Note that methodinfo has been obtained before the call. Maybe the biggest performance problem of reflection should be "loading the Assembly, getting classes, and getting method information, therefore, as long as methodinfo is obtained during the first call in the program and used directly in the future, there is no efficiency issue to worry about, unless you are stupid enough to do a series of actions such as "loading the Assembly, getting classes, and getting method information" during each call.
Conclusion: As long as methodinfo is obtained in advance (for the first time, it will be used directly later), there will be 1 millisecond Errors for more than 10000 calls, and there is no worry about efficiency at all, feel free to use reflection!