Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C# compiler strip out empty methods?

Tags:

c#

compilation

I put a debug print codes everywhere when I am fixing codes, when I am done with it I did not remove them but put a comment so that when the bug occurs around here next I would be able to uncomment it and get it to print out data.

(I can't get used to breakpoint debugging and inspecting variables, and I found putting debug print I can get the timing that I want the message to appear better.)

If possible I would like to be able to switch the debug code on and off more easily but since they are all spread out, commenting/uncommenting is a pain. Putting #if preprocessor should work but a one line debug print becomes 3 lines #if Debug #endif everywhere.

So I have an idea to wrap the debug method with my own, and inside it is just #if check before the actual debug method. My question is when the #if directive is false the function becomes empty, will the compiled code still jumps to this empty function? I am worried especially if this empty method is in a core game loop and being called multiple thousand times per seconds.

Also if it really get stripped out, I wonder if the parameter data remains in the program? For example if I write MyDebug("Encryption key : " + key); will that string remains in the code if the method is empty?

like image 231
5argon Avatar asked Jan 03 '23 16:01

5argon


1 Answers

The compiler won't strip out empty methods because it has no way of knowing that they won't be called (even if they are private - due to reflection).

However you can use ConditionalAttribute to do this the same way as .Net does for Debug.WriteLine() etc:

[Conditional("DEBUG")]
public static void MyDebugOnlyMethod()
{
    ...
}

This will cause the compiler to omit from the compiled code that method and all calls to it, unless the "DEBUG" conditional symbol is defined at compile time.

This is a bit more readable than using #if DEBUG ... #endif

Also note that you don't have to use "DEBUG" - you can use any other string that you want, but you would than have to define it when needed using #define or by setting a conditional compilation symbol in the project settings.

like image 77
Matthew Watson Avatar answered Jan 05 '23 16:01

Matthew Watson