开发者

.Net optimization

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 empt开发者_JAVA百科y method overhead?

Regards,


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜