In .NET, will empty method calls be optimized out?

前端 未结 4 1224
时光说笑
时光说笑 2021-01-07 17:41

Given an empty method body, will the JIT optimize out the call (I know the C# compiler won\'t). How would I go about finding out? What tools should I be using and where shou

相关标签:
4条回答
  • 2021-01-07 18:13

    I'm guessing your code is like:

    void DoSomethingIfCompFlag() {
    #if COMPILER_FLAG
        //your code
    #endif
    }
    

    This won't get optimised out, however:

    partial void DoSomethingIfCompFlag();
    
    #if COMPILER_FLAG
    partial void DoSomethingIfCompFlag() {
        //your code
    }
    #endif
    

    The first empty method is partial, and the C#3 compiler will optimise it out.


    By the way: this is basically what partial methods are for. Microsoft added code generators to their Linq designers that need to call methods that by default don't do anything.

    Rather than force you to overload the method you can use a partial.

    This way the partials are completely optimised out if not used and no performance is lost, rather than adding the overhead of the extra empty method call.

    0 讨论(0)
  • 2021-01-07 18:15

    No, empty methods are never optimized out. Here are a couple reasons why:

    • The method could be called from a derived class, perhaps in a different assembly
    • The method could be called using Reflection (even if it is marked private)

    Edit: Yes, from looking at that (exellent) code project doc the JITer will eliminate calls to empty methods. But the methods themselves will still be compiled and part of your binary for the reasons I listed.

    0 讨论(0)
  • 2021-01-07 18:28

    All things being equal, yes it should be optimized out. The JIT inlines functions where appropriate and there are few things more appropriate than empty functions :)

    If you really want to be sure then change your empty method to throw an exception and print out the stack trace it contains.

    0 讨论(0)
  • 2021-01-07 18:36

    This chap has quite a good treatment of JIT optimisations, do a search on the page for 'method is empty', it's about half way down the article -

    http://www.codeproject.com/KB/dotnet/JITOptimizations.aspx

    Apparently empty methods do get optimised out through inlining what is effectively no code.

    @Chris: I do realise the that the methods will still be part of the binary and that these are JIT optimisations :-). On a semi-related note, Scott Hanselman had quite an interesting article on inlining in Release build call stacks:

    http://www.hanselman.com/blog/ReleaseISNOTDebug64bitOptimizationsAndCMethodInliningInReleaseBuildCallStacks.aspx

    0 讨论(0)
提交回复
热议问题