On. NET reflection mechanism performance Optimization with example download _ Practical Tips

Source: Internet
Author: User
Tags reflection
Maybe everyone talks about the facial muscles that are starting to twitch! Because in the managed language, the most notorious is reflection! Its performance is really too low, even in many cases we can not stand. But not so tangled, old Chen today to share how to optimize the reflection!

Overview
The following two kinds of methods are involved in the reflection optimization:

To optimize by creating delegates through Delegate.createdelegate ()
Pass. NET4 Dynamic Runtime optimization
If you also know other more effective ways to optimize, please do not hesitate to enlighten!

preparatory work
Today we have a total of five different ways of calling object members, which is a performance test.

Before we begin, we first define a simple object and a method for testing purposes:
Copy Code code as follows:

Namespace Reflectionoptimization
{
public sealed class Testobject
{
public int Add (int a, int b)
{
Simple Demo
return a + B;
}
}
}

This class is very simple and provides only one method, which returns two of the integer's and. Let's take a look at the code that executes the time measurement, and it's easy to assume that you've got the Knack:
Copy Code code as follows:

private static double _run (string description, Action<int, int> Action, int a, int b)
{
if (action = null) throw new ArgumentNullException ("action");

Start timer
var stopwatch = stopwatch.startnew ();

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

Stop timing
Stopwatch. Stop ();

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

Return Execution time
Return stopwatch. Elapsed.totalmilliseconds;
}

The above method of measuring time returns the execution time, because we want to use this value in the back, after executing several times to take an average, in order to test the fairness, authority.

Coding Implementation
First, let's take a look at the implementation of the primary reflection:
Copy Code code 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});

And then we'll see. Implementation of NET4 dynamic programming:
Copy Code code as follows:

Dynamic obj = new Testobject ();

There is wood to find this code super simple?
for (var i = 0; i < _times i++) obj. Add (A, b);

Finally, let's look at how to use delegates to optimize reflection:
Copy Code code as follows:

Commissioned
public delegate int Addmethod (int a, int b);

Realize
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 code above looks a few more lines, and you need to customize a delegate, which is cumbersome to write. So our test code also implements another form, in fact it is also a delegate:

var d = (func<testobject, int, int, int>) delegate.createdelegate (typeof (Func<testobject, int, int, int>), Add);

Test Summary
We first run the entire test code 5 times in debug mode, then record the average, and then repeat the test in release mode.

The testing process is no longer elaborated and the test results are collated as follows:

Debug mode:

Call Mode First time second time third time fourth time Fifth time
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 Mode First time second time third time fourth time Fifth time
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 & Conclusions:

    • After using a delegate to optimize reflection, its performance is similar to that of a direct call, maintained within the same order of magnitude, and is recommended when performance requirements are extremely demanding;
    • Explicit delegate (Delegate) and anonymous Delegate (FUNC) performance differences are very inconspicuous, but the performance of explicit delegates is better;
    • The native delegate is two orders of magnitude slower than the direct call, and the performance difference is 200 times times more!
    • The dynamic programming syntax for. NET 4 is fairly concise, and its performance is only one order of magnitude higher than a direct call, which we recommend because of its fairly concise syntax!
    • The primary reflection technology is not very different in debug mode and release mode, but other methods have obvious optimization effect (please think why);
    • Although our tests today do not fully imply that reflection optimization can be compared to direct invocation, it can at least somehow defeat those rumors--who says that reflection must be slow (hehe)!

Code Download: A brief talk on reflection optimization

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.