Introduction to. NET reflection mechanism performance optimization

Source: Internet
Author: User

Maybe you have started to twenty your facial muscles! In hosting languages, reflection is the most notorious! Its performance is too low, and it is sometimes intolerable. But you don't have to worry about it. Let's talk about how to optimize reflection today!

Overview
The reflection optimization methods involved in this article are as follows:

Use Delegate. CreateDelegate () to create a Delegate for Optimization
Optimized during dynamic running through. NET4
If you still know other more effective optimization methods, please do not hesitate to give us your advice!

Preparations
Today, we have to compare five different methods of calling object members, which is also a performance evaluation.

Before getting started, we first define a simple object and a method for testing:
Copy codeThe Code is as follows:
Namespace ReflectionOptimization
{
Public sealed class TestObject
{
Public int Add (int a, int B)
{
// Simple demonstration
Return a + B;
}
}
}

This class is very simple and only provides one method. This method returns the sum of two integers. Next, let's take a look at the code for executing the time measurement. It's very simple. You must be familiar with it:
Copy codeThe Code is as follows:
Private static double _ Run (string description, Action <int, int> action, int a, int B)
{
If (action = null) throw new ArgumentNullException ("action ");

// Start the timer
Var stopwatch = Stopwatch. StartNew ();

// Run the code to be measured
Action (a, B );

// Terminate timing
Stopwatch. Stop ();

// Output result
Console. WriteLine ("{0 }:{ 1}", description, stopwatch. Elapsed. TotalMilliseconds. ToString (CultureInfo. InvariantCulture ));

// Return the execution time
Return stopwatch. Elapsed. TotalMilliseconds;
}

The preceding measurement time method returns the execution time, because we need to use this value later and take an average value after multiple executions for the fairness and authority of the test.

Coding implementation
First, let's look at the implementation of native reflection:
Copy codeThe Code is as follows:
Var obj = new TestObject ();
Var add = obj. GetType (). GetMethod ("Add ");

For (var I = 0; I <_ TIMES; I ++) add. Invoke (obj, new object [] {a, B });

Then let's take a look at the implementation of. NET4 dynamic programming:
Copy codeThe Code is as follows:
Dynamic obj = new TestObject ();

// Is it super easy to find this code?
For (var I = 0; I <_ TIMES; I ++) obj. Add (a, B );

Finally, let's take a look at how to use delegation to optimize reflection:
Copy codeThe Code is as follows:
// Delegate
Public delegate int AddMethod (int a, int B );

// Implementation
Var obj = new TestObject ();
Var objType = obj. GetType ();
Var add = objType. GetMethod ("Add ");
Var d = (AddMethod) Delegate. CreateDelegate (typeof (AddMethod), obj, add );

For (var I = 0; I <_ TIMES; I ++) d (a, B );

The above code looks a few more lines and requires a custom delegate, which is quite troublesome to write. Therefore, our test code also implements another form. In fact, it is also a delegate:

Var d = (Func <TestObject, int>) Delegate. CreateDelegate (typeof (Func <TestObject, int>), add );

Test Summary
We first run the entire test code five times in Debug mode, then record the average value, and then repeat the test in Release mode.

The test process is not described. The test results are as follows:

Debug mode:

Call Method First time Second Third time Fourth Fifth
Generic Call 1.022425 1.012885 0.990775 1.020950 1.046880
Reflection 147.489220 146.012010 142.690080 139.189335 141.663475
Dynamic 9.645850 9.979965 9.307235 9.532665 9.730030
Func 1.201860 1.214800 1.170215 1.189280 1.239485
Delegate 1.062215 1.061635 1.067510 1.047180 1.075190

Release mode:

Call Method First time Second Third time Fourth Fifth
Generic Call 0.745600 0.741365 0.722145 0.732630 0.725645
Reflection 141.778260 142.855410 142.346095 139.649990 138.541285
Dynamic 9.631460 10.341850 9.284230 9.457580 9.060470
Func 0.882100 0.852680 0.875695 0.854655 0.831670
Delegate 0.710280 0.722465 0.723355 0.727175 0.693320

Comments and conclusions:

  • After delegate optimization reflection is used, its performance is almost the same as that of direct calls, which is kept within the same order of magnitude. This solution is recommended when the performance requirements are extremely demanding;
  • The performance difference between explicit delegation and anonymous delegation is not obvious, but the performance of explicit delegation is better;
  • Native delegation is two orders of magnitude slower than direct calls, and the performance difference has reached 200 times!
  • The Dynamic Programming Syntax of. NET 4 is quite concise, and its performance is only one order of magnitude higher than that of direct calls. Because of its concise syntax, we recommend this practice!
  • Native reflection technology does not differ much in Debug mode and Release mode, but other methods have obvious optimization effects (please think about why );
  • Although our tests today cannot completely mean that reflection optimization can be comparable to direct calls, but at least those rumors can be defeated to some extent-who says reflection will be slow (giggle )!

Code download: Reflection Optimization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.