Comparison of several reflection mechanisms in C #

Source: Internet
Author: User
1. Foreword

Reflection is an interesting technique, and she offers another perspective to blur and unify the small World we build with code. As a result of the previous work of the relationship, the small fish sauce has used C + + slightly to implement a set of reflection system, used to support the development of the property editor in the game, in C + + reflection is an injection or later generated a programming way, will lead to code difficult to read, out of the beauty of But the reflection in C # is natural and graceful.
Because recently in doing hand tour development, began to study Unity3d, began to regain a long absence of C #. So the fish sauce below will briefly introduce the reflection technology in C #, and compare the performance of each way through function call.
2. Several reflection mechanisms 2.1. Primary Reflection

C # provides powerful, complete reflection functionality through the System.Reflection assembly, enabling us to get "assembly", "module", "type", and so on during the program run, and she also provides a common way of accessing and using this information. So we in the world of code, in the face of different "people" or "things", there is an arrogant same accent.
Here we only discuss function calls, followed by the function call to compare the performance of each reflection mechanism.
There are two more commonly used "moves" for function invocation under the frame of native reflection. were as follows:

1. Through MethodInfo
Calling a function abstract as a function method object is less efficient.

    <summary>
    ///Native reflection test
    ///</summary> public
    class Nativereflecttest
    {
        ///< Summary>
        ///Run
        ///</summary> public
        static void run ()
        {
            //Type Object type
            PersonType = typeof (person);
            
            Method information
            MethodInfo MethodInfo = Persontype.getmethod ("Say");

            The object and the parameter person person
            = The new Person ();
            String word = "";
            object[] param = new object[] {word, 0};

            The maximum number of times to invoke the test run time
            profiler.start ();
            for (int i = 0; i < 1000000 i++)
            {
                param[1] = i;
                Methodinfo.invoke (person, param);
            Profiler.stopandprint ("1000000 times invoked by Reflection:");
        }
    


2. Through assembly
The direct object is generated with assembly, and then the call period is equivalent to calling the function directly.

    <summary>
    ///Assembly test
    ///</summary> public
    class Assemblytest
    {
        ///<summary >
        ///Run
        ///</summary> public
        static void run ()
        {
            Assembly Assembly = Assembly.Load (" Fastmethodinvoker ");
            Person person = assembly. CreateInstance ("FastMethodInvoker.example.subject.Person") as person;

            String word = "";

            Profiler.start ();
            for (int i = 0; i < 1000000, ++i)
            {person
                . Say (ref word, I);
            }
            Profiler.stopandprint ("1000000 times invoked by Assembly:");
        }
    


2.2. Commission (delegate)

        In fact, the agent itself is not directly related to reflection, just because we are talking about function calls, and delegates are inherently the lifeblood of function calls.
        relative to native reflection, delegates appear to be more specific, and he needs to define the types of delegates for each function in a different form, and then bind them on functions of different classes. Delegates are somewhat weaker than the abstract abstraction of native reflection. The
         binding delegate's "Moves" are as follows:

    public delegate void Sayhandle (ref String Word, int count);

    <summary>
    ///Agent Test
    ///</summary> public
    class DelegateTest
    {
        ///<summary >
        ///Run
        ///</summary> public
        static void run ()
        {
            Type type = typeof (person);

            MethodInfo MethodInfo = type. GetMethod ("Say");

            person who = new person ();
            String word = "";
            Sayhandle delegateobject = Delegate.createdelegate (typeof (Sayhandle), person, methodInfo) as Sayhandle;

            Profiler.start ();
            for (int i = 0; i < 1000000 i++)
            {
                delegateobject (ref word, i);
            Profiler.stopandprint ("1000000 times invoked by delegate:");
        }
    


2.3. Quick call (fast invoke)

         A Fastinvoke method is introduced on CodeProject to perform function reflection. Compared to native reflection, she provides a more low-level way to implement it. The MSIL language is primarily used to create instruction streams to achieve the same execution efficiency as the calling period and normal code. The
         msil language, known as the Microsoft Intermediate Language, is used primarily for cross-platform support, C # Generates the MSIL code to the machine code of the current machine. In Fastinvoke, the MSIL code that invokes the function is generated directly, which is equivalent to writing code that calls the function directly from C #.
         in the interface after the small fish sauce is packaged, the "moves" of the Fastinvoke method are as follows:

    <summary>
    ///Quick Call Test
    ///</summary> public
    class Fastinvoketest
    {
        ///< Summary>
        ///Run
        ///</summary> public
        static void run ()
        {
            //Quick call
            handle Fastinvokehandler Fastinvoker = fastinvoker.createhandler<person> ("Say");

            The object and the parameter person person
            = The new Person ();
            String word = "";
            object[] param = new object[] {word, 0};

            The maximum number of times to invoke the test run time
            profiler.start ();
            for (int i = 0; i < 1000000 i++)
            {
                param[1] = i;
                Fastinvoker (person, param);
            Profiler.stopandprint ("1000000 times invoked by Fastinvoke:");
        }
    



Here is the source code address: Http://www.codeproject.com/Articles/14593/A-General-Fast-Method-Invoker
Here's the little fish sauce. After finishing the code address: Http://pan.baidu.com/s/1hqAajuG

3. Performance comparison

Here is an experiment of several reflection invocations, which call a simple function of a maximum number of times (1 million), as follows:

    Class program
    {
        static void Main (string[] args)
        {
            //Classic Reflection Test
            nativereflecttest.run ();

            Quick Call Test
            fastinvoketest.run ();

            Assembly
            Assemblytest.run ();

            Agent
            Delegatetest.run ();

            Direct call Test
            directinvoketest.run ();

            Console.ReadLine ();
        }
    


Performance results:

The conclusion is that the time consumption of the native call is quite different from that of the direct call, and assembly need to build the object by reflection, then access the function by the way of direct call, and the performance efficiency of the object is not statistically, if the statistical process is added, The performance of the Assembly method is lower than the native invocation, while the assembly method destroys the unified abstraction required by the reflection. The delegate method is actually a direct call, but the same thing with assembly is that he also destroys the unified abstraction needed for reflection. Fastinvoke is not much different from direct invocation performance and maintains a uniform form of access.

This is the project address for performance comparisons: Http://pan.baidu.com/s/1hqAajuG

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.