Reflection expression tree DLR performance, efficiency comparison

Source: Internet
Author: User
Tags static class

I've seen a variety of reflection and expression tree performance comparisons from the Internet. So I wrote the code to test. found that the cycle 100,000 times below the performance difference is not significant.





<%@ Page language= "C # autoeventwireup=" true "codefile=" performance comparison of the reflection expression tree DLR. Aspx.cs "inherits=" sequence Reflection motion Set _ Reflection expression tree DLR performance comparison "%>

<! DOCTYPE html>








Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;

Using System.Web.UI.WebControls; Public partial class sequence reflection motion Set _ Reflection expression tree DLR performance comparison: System.Web.UI.Page {protected void Page_Load (object sender, EventArgs


        e) {//Fill data Action act = () => {inittypepropertyassignexpression<testcalass> (true); Response.Write ("Conversion Complete:" + act.)


        Stopwatchrun () + "millisecond <br/>");

        list<double> lis = new list<double> () {0.1, 0.5, 10, 20, 30, 50,100,200};
        The different cycles are compared to foreach (double num in lis) {Rundiff (num);
    #region padding and calculation method Random dom = new Random (); <summary>///Start comparison method///</summary>///<param name= "num" > How many times to compare </param> publ IC void Rundiff (double num = 10) {//100,000 time calculated vs. var arr = System.Linq.Enumerable.Range (1, (int) (NUM * 10000)).

        ToList (); Testcalass C = new Testcalass (); Action manual encoding = () => {arr.
            ForEach ((o) => {produces random values and fills the image (C, 2);
        });

        }; Action expression tree = () => {arr.
                ForEach ((o) => {//testcalass c = new Testcalass ();

            Generates random values and fills the image (c, 0);
        });


        }; Action reflection = () => {arr.
                ForEach ((o) => {//Testcalass c = new Testcalass ();
            Generates random values and fills the image (c, 1);
        });

        };

        Long V0, v1, v2; Response.Write (String. Format ("{0}" runs {1} million times, spents {2} milliseconds <br/> ", Manual Encoding", arr.) count/10000.0, v2 = manual encoding.
        Stopwatchrun ())); Response.Write (String. Format ("{0}" runs {1} million times, spents {2} milliseconds <br/>, "expression tree", arr.) count/10000.0, V0 = expression tree.
        Stopwatchrun ())); Response.Write (String. Format ("{0}" runs {1} million times, spents {2} milliseconds <br/> ", reflection Assignment, arr.") count/10000.0, V1 = reflection. StopWatchrun ())); Response.Write (String.   Format (' {0} ' is the base value {1} when {2};
        {3} when {4} difference: {5}, fast {6} times ", V2," Expression tree ", v0-v2," Reflection Assignment ", V1-v2 (V1-v0), (v1-v0)/(V0-V2)); Response.Write (String.

    Format ("--------------------------<br/>")); ///<summary>///Set reflection data///</summary> public void Refsetvalue (System.Reflection.PropertyI
    NFO p, Testcalass T, object val) {P.setvalue (T, Val, NULL); 

            public void generates random values and fills the image (Testcalass c, int isexpression = 1) {foreach (var p in Exproinfodic) { if (P.value.propertytype = = typeof (int)) {int val = dom. Next (1, Int.)
                MaxValue); Whether to use an expression assignment if (isexpression = 0) {//Pass value P.value.
                    Actionassign (Val, c);
                Continue } if (isexpression = = 1) {Refsetvalue (p.value.prOpertyinfo, C, Val);
                Continue
                    } if (isexpression = = 2) {c.a = val;
                Continue } if (P.value.propertytype = = typeof (String)) {string val = Guid. NewGuid ().
                ToString (); Whether to use an expression assignment if (isexpression = 0) {//Pass value P.value.
                    Actionassign (Val, c);
                Continue
                    } if (isexpression = = 1) {Refsetvalue (P.value.propertyinfo, C, Val);
                Continue
                    } if (isexpression = = 2) {c.b = val;
                Continue } if (P.value.propertytype = = typeof (DateTime)) {int vald = dom. Next (1, Int.)
MaxValue);                DateTime val = DateTime.Now.AddMilliseconds (Vald); Whether to use an expression assignment if (isexpression = 0) {//Pass value P.value.
                    Actionassign (Val, c);
                Continue
                    } if (isexpression = = 1) {Refsetvalue (P.value.propertyinfo, C, Val);
                Continue
                    } if (isexpression = = 2) {c.c = val;
                Continue } if (P.value.propertytype = = typeof (double[))) {double[] val = ne
                W DOUBLE[50]; for (int i = 0; i < val. Length; i++) {Val[i] = dom. Next (1, Int.)
                MaxValue);
                    //whether to use an expression to assign the value if (isexpression = 0) {//Pass value P.value.aCtionassign (Val, c);
                Continue
                    } if (isexpression = = 1) {Refsetvalue (P.value.propertyinfo, C, Val);
                Continue
                    } if (isexpression = = 2) {C.arr = val;
                Continue #endregion///<summary>///Initialization Type property expression operation, can only handle primitive type///</sum mary>///<exception cref= "System.Collections.Generic.KeyNotFoundException" > did not find a suitable solution </exception >///<param name= "Notfindconvertobject" > did not find an appropriate type of automatic conversion to object</param> public void Inittypepropertyas Signexpression<t> (bool Notfindconvertobject = false) {//Initialize expression foreach (var p in typeof (T).
            GetProperties ()) {//c# All primitive types if (createexpression<t, byte> (p)) {continue;} if (createexpression<
            T, Sbyte> (p)) {continue}
            if (Createexpression<t, int> (p)) {continue;}
            if (Createexpression<t, uint> (p)) {continue;}
            if (Createexpression<t, short> (p)) {continue;}
            if (Createexpression<t, ushort> (p)) {continue;}
            if (Createexpression<t, long> (p)) {continue;}
            if (Createexpression<t, ulong> (p)) {continue;}
            if (Createexpression<t, float> (p)) {continue;}
            if (Createexpression<t, double> (p)) {continue;}
            if (Createexpression<t, char> (p)) {continue;}
            if (Createexpression<t, bool> (p)) {continue;}
            if (Createexpression<t, string> (p)) {continue;}
            if (Createexpression<t, decimal> (p)) {continue;}
            if (Createexpression<t, object> (p)) {continue;}

            if (Createexpression<t, datetime> (p)) {continue;} if (NotfindconVertobject) {////no suitable type automatically converted to object createexpression<t, Object> (P, Tru
            e);

            else {throw new KeyNotFoundException ("No suitable primitive type found"); }}///<summary>///create property Expression data entity///</summary>///<typeparam name= "T" > Type </typeparam>///<typeparam name= "TValue" > property value type </typeparam>///<param name= "P" > attribute information &L 
    t;/param>///<param name= "Toobject" > Convert to object</param>///<returns> successful return true</returns>

        protected bool Createexpression<t, tvalue> (System.Reflection.PropertyInfo p, bool Toobject = False) { if (P.propertytype = = typeof (TValue) | | toobject) {//Add to cache collection return Exproinfodic.trya DD (p.name, new Expressionpropertyinfo () {propertytype = P.propertytype, Pr
Opertyname = P.name,                 PropertyInfo = p, actionassign = Getexpression<t, tvalue> (P.name)});
    return false; ///<summary>///Expression type attribute information to like cache///</summary> System.Collections.Concurrent.ConcurrentDict ionary<string, expressionpropertyinfo> exproinfodic = new System.Collections.Concurrent.ConcurrentDictionary


    <string, expressionpropertyinfo> (); <summary>///A Property-transfer operation expression///</summary>///<param name= ' PropertyName ' > property name &LT;/PARAM&G
    T <typeparam name= "T" > Entity type value </typeparam>///<typeparam name= "TValue" > attribute type value </typeparam>/ <returns></returns> public Func<tvalue, T, tvalue> getexpression<t, tvalue> (string property
        Name) {Type t = typeof (T);
        System.Reflection.PropertyInfo Pro = T.getproperty (PropertyName);
    Return getexpression<t, tvalue> (PRO); }

    ///<summary>///A Property-transfer operation expression///</summary>///<param name= "PropertyInfo" > attribute to like </param>
    <typeparam name= "T" > Entity type value </typeparam>///<typeparam name= "TValue" > attribute Type value </typeparam> <returns></returns> public Func<tvalue, T, tvalue> getexpression<t, tvalue> (SYSTEM.REFL Ection.
        PropertyInfo PropertyInfo) {Type t = typeof (T);
        Type vt = typeof (TValue);
        Parameter p System.Linq.Expressions.ParameterExpression p = System.Linq.Expressions.Expression.Parameter (t, "P");

        Parameter value v System.Linq.Expressions.ParameterExpression v = System.Linq.Expressions.Expression.Parameter (vt, "V"); Property curp System.Linq.Expressions.MemberExpression curp = System.Linq.Expressions.Expression.Property (P,


        PropertyInfo);
        Assignment operation System.Linq.Expressions.BinaryExpression ass = null;
           if (VT!= propertyinfo.propertytype) { Conversion expression v System.Linq.Expressions.UnaryExpression conv = System.Linq.Expressions.Expression.Convert (V, proper
            Tyinfo.propertytype);

        Assignment Operation ass = System.Linq.Expressions.Expression.Assign (curp, conv);
        else {ass = System.Linq.Expressions.Expression.Assign (curp, v); }//Expression results system.linq.expressions.expression<func<tvalue, T, tvalue>> result = SYSTEM.LINQ.E Xpressions.

        Expression.lambda<func<tvalue, T, tvalue>> (Ass, V, p);

    Returns the compiled result return result.compile ();
        ///<summary>///Expression type attribute information to like///</summary> public class Expressionpropertyinfo {

        <summary>///Property name///</summary> public string propertyname {get; set;}

        <summary>///Property Type///</summary> public type propertytype {get; set;}
  <summary>      Property pairs like///</summary> public System.Reflection.PropertyInfo PropertyInfo {get; set;} 

    <summary>///Assignment Operation Delegate///</summary> public dynamic actionassign {get; set;} ///<summary>///Test class///</summary> public class Testcalass {public in

        t a {get; set;}

        public string B {get; set;}

        Public DateTime c {get; set;}

    Public double[] ARR {get; set;} }
}


Extension methods

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace System
{
    ///<summary>
    ///Common Debugging Method
    ///</summary> public
    Static class Tongtestexpand
    {

        ///<summary>
        ///Test This method run time
        ///</summary>
        ///<param name= "Act" > Run method </param>
        ///<returns> return time Unit MS </returns> public
        static Long Stopwatchrun ( This Action Act)
        {
            System.Diagnostics.Stopwatch sa = new System.Diagnostics.Stopwatch ();
            Long result = 0;
            Sa. Restart ();

            Try
            {
                Act ();
            }
            Finally
            {

                SA. Stop ();
                result = sa. elapsedmilliseconds;
            }
            return result
        }}

    }


Run result 1 (do not need to create values every time)

Conversion complete: 11 milliseconds to run 1000 times manual encoding, 7 millisecond expression tree run 1000 times, spents 48 millisecond reflection assignment to run 1000 times, spents 6 milliseconds 7 as the base value expression tree when 41;  Reflection assignment When-1 difference:-42, fast-1 time Times--------------------------Manual encoding run 5,000 times, time 18 milliseconds expression tree run 5,000 times, spents 22 millisecond reflection assignment 5,000 times, spents 33 milliseconds 18 as the base value Expression tree spents 4; Reflection Assignment Time 15 difference: 11, fast twice times--------------------------manual encoding run 100,000 times, time 403 milliseconds expression tree run 100,000 times, spents 445 millisecond reflection assignment 100,000 times, spents 667 milliseconds 403 as the base value Expression tree Spents 42; Reflection Assignment Time 264 difference: 222, Fast 5 times Times--------------------------manual encoding run 200,000 times, time 784 milliseconds expression tree run 200,000 times, spents 901 millisecond reflection assignment run 200,000 times, spents 1348 milliseconds 784 as base The quasi-value expression tree is 117; Reflection Assignment Time 564 difference: 447, fast 3 times times--------------------------manual encoding run 300,000 times, time 1178 milliseconds expression tree run 300,000 times, spents 1344 millisecond reflection assignment run 300,000 times, spents 2003 milliseconds 117 8 is the base value expression tree Spents 166; Reflection Assignment Time 825 difference: 659, fast 3 times times--------------------------manual encoding run 500,000 times, time 1987 milliseconds expression tree run 500,000 times, spents 2285 millisecond reflection assignment run 500,000 times, spents 3396 milliseconds 198 7 is the base value expression tree spents 298; Reflection Assignment Time 1409 difference: 1111, fast 3 times times--------------------------Manual encoding Run 1 million times, time 4013 milliseconds expression tree run 1 million times, spents 4625 millisecond reflection assignment to run 1 million times, when 6798 cents The second 4013 is the base value expression tree when 612; Reflection Assignment Time 2785 difference: 2173, fast 3 times times--------------------------Manual encoding Run 2 million times, spents 8277 milliseconds expression tree Run 200Million times, spents 9281 millisecond reflection assignment runs 2 million times, spents 13773 milliseconds 8277 as the base value expression tree when 1004; Reflection assignment when 5496 difference: 4492, faster than 4 times times--------------------------



Run effect 2 (values are created each time in the method)

Conversion complete: 11 milliseconds to run 1000 times manual encoding, 7 millisecond expression tree run 1000 times, spents 48 millisecond reflection assignment to run 1000 times, spents 6 milliseconds 7 as the base value expression tree when 41;  Reflection assignment When-1 difference:-42, fast-1 time Times--------------------------Manual encoding run 5,000 times, time 18 milliseconds expression tree run 5,000 times, spents 22 millisecond reflection assignment 5,000 times, spents 33 milliseconds 18 as the base value Expression tree spents 4; Reflection Assignment Time 15 difference: 11, fast twice times--------------------------manual encoding run 100,000 times, time 403 milliseconds expression tree run 100,000 times, spents 445 millisecond reflection assignment 100,000 times, spents 667 milliseconds 403 as the base value Expression tree Spents 42; Reflection Assignment Time 264 difference: 222, Fast 5 times Times--------------------------manual encoding run 200,000 times, time 784 milliseconds expression tree run 200,000 times, spents 901 millisecond reflection assignment run 200,000 times, spents 1348 milliseconds 784 as base The quasi-value expression tree is 117; Reflection Assignment Time 564 difference: 447, fast 3 times times--------------------------manual encoding run 300,000 times, time 1178 milliseconds expression tree run 300,000 times, spents 1344 millisecond reflection assignment run 300,000 times, spents 2003 milliseconds 117 8 is the base value expression tree Spents 166; Reflection Assignment Time 825 difference: 659, fast 3 times times--------------------------manual encoding run 500,000 times, time 1987 milliseconds expression tree run 500,000 times, spents 2285 millisecond reflection assignment run 500,000 times, spents 3396 milliseconds 198 7 is the base value expression tree spents 298; Reflection Assignment Time 1409 difference: 1111, fast 3 times times--------------------------Manual encoding Run 1 million times, time 4013 milliseconds expression tree run 1 million times, spents 4625 millisecond reflection assignment to run 1 million times, when 6798 cents The second 4013 is the base value expression tree when 612; Reflection Assignment Time 2785 difference: 2173, fast 3 times times--------------------------Manual encoding Run 2 million times, spents 8277 milliseconds expression tree Run 200Million times, spents 9281 millisecond reflection assignment runs 2 million times, spents 13773 milliseconds 8277 as the base value expression tree when 1004; Reflection assignment when 5496 difference: 4492, faster than 4 times times--------------------------


and online (said 100 times times there is a big difference)



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.