Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 should I be looking?

Since I'm sure it'll be asked, the reason for the empty method is a preprocessor directive.


@Chris: Makes sense, but it could optimize out calls to the method. So the method would still exist, but static calls to it could be removed (or at least inlined...)

@Jon: That just tells me the language compiler doesn't do anything. I think what I need to do is run my dll through ngen and look at the assembly.

like image 511
Karl Seguin Avatar asked Aug 14 '08 23:08

Karl Seguin


2 Answers

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

like image 184
Kev Avatar answered Sep 18 '22 06:09

Kev


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.

like image 23
Keith Avatar answered Sep 20 '22 06:09

Keith