Reputation: 4938
class Debug
{
internal static void Assert(bool condition)
{
#if DEBUG
Log.Out("Asserted");
#endif
}
}
Will the compiler get rid of calling Assert, as it's empty in Release builds and Optimize checkbox is checked, or there will be a calling empty method overhead?
Regards,
Upvotes: 2
Views: 521
Reputation: 1503639
No, the C# compiler won't remove the call to Assert
- it'll just be an empty method. The JIT compiler may optimize it away in calling code; effectively that's a special case of inlining, where the result of inlining is "nothing to execute". However, note that the argument to Assert
will still be evaluated.
However, if you want to make the call itself conditional, a cleaner approach is to change the method to use the System.Diagnostics.Conditional
attribute:
[Conditional("DEBUG")]
internal static void Assert(bool condition)
{
Log.Out("Asserted");
}
This changes the semantics: now the whole method call including argument evaluation will be removed by the C# compiler, so you could have:
Assert(GetCountOfAllRowsInDatabase() != 0);
and in debug mode it would hit the database, but in release mode it wouldn't.
Upvotes: 13
Reputation: 23591
AFAIK the whole thing will be optimized away at JIT compile time. The JIT compiler will try to inline the method since it is short and will have noting to inline. On the C# side it will be an empty method. You'll be able to see it in the compiled assembly but since it is internal it should not matter.
Upvotes: 1
Reputation: 17111
According to this, http://www.dotnetperls.com/jit
From what I understand of the article, it appears that the C# compiler does not remove the method from the code. However the JIT compiler removes the calls to the methods.
Upvotes: 1