简体   繁体   中英

Any one know how exactly IL/CLR generates Local Functions C#7

https://www.infoworld.com/article/3182416/c-7-in-depth-exploring-local-functions.html

I really need to know exactly following code how Local Functions supposed to be.

Am 0% IL Code/MSIL experience.

  public static void Display(string str)
    {
        int ctr = 5;
        DisplayText();

        void DisplayText ()
        {
            for(int i = 0; i < ctr; i++)
            Console.WriteLine(str);
        }
    }

Question I need to know here from previous code:

  1. If we call main function Display() does Local Function DisplayText() always generated when main one called? Or it created as a fake local function in C# but in MSIL it generated as Global function?
  2. In lamda expression method? does it same above?
  3. Is it safe to depend on local functions? or shall we not used it anyway. (performance maybe idk )

Edit:- I think Local Properties (which not exists yet or maybe...). it is useful also sometimes. which you can have some calculation in same Method as a local property. as previous example but DisplayText are property. Wish they add it also.

CIL and the runtime have no concept of a local function, instead the C# compiler translates it into a normal method with private visibility and potentially a class/struct used to share state with the declaring method. You can see this for yourself by compiling the code and then decompiling the assembly, or by using a site such as SharpLab.io .

Lambda expressions and anonymous methods are very similar, except that they need to provide a delegate which can limit the optimization opportunities.

The compiler puts a lot of effort into optimizing the generated code, I would not expect local methods to affect performance much beyond what you would get for any other method. I would suggest you focus more on how it affects maintainability, at least until you can identify an actual performance problem by profiling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM