gpt4 book ai didi

c# - C# 编译器是否删除了封装 debug.writeline 的 if

转载 作者:IT王子 更新时间:2023-10-29 03:59:55 24 4
gpt4 key购买 nike

我有一段代码是这样的:

if (state != "Ok")
{
Debug.WriteLine($"Error occured: {state}, {moreInfo}");
}

如果我进行发布构建,编译器会优化它吗?还是评估会停留并因此花费一些处理时间?

最佳答案

是的,至少对于 Debug 调用是这样。我在这里看不到 JIT 编译器是否也删除了 if 的求值,但我猜是这样,因为等式没有任何副作用。

但是,您最好通过调用 Debug.WriteLineIf 来保证它的安全,这不依赖于 JIT 编译器来删除评估。

为了完整性,编译器删除了 Debug.WriteLine


发布版本中的代码:

.method public hidebysig static void  Main(string[] args) cil managed
{
.entrypoint
// Code size 17 (0x11)
.maxstack 8
IL_0000: call string [mscorlib]System.Console::ReadLine()
IL_0005: ldstr "Ok"
IL_000a: call bool [mscorlib]System.String::op_Inequality(string,
string)
IL_000f: pop
IL_0010: ret
} // end of method Program::Main

调试构建中的代码:

.method public hidebysig static void  Main(string[] args) cil managed
{
.entrypoint
// Code size 42 (0x2a)
.maxstack 2
.locals init ([0] string state,
[1] bool V_1)
IL_0000: nop
IL_0001: call string [mscorlib]System.Console::ReadLine()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldstr "Ok"
IL_000d: call bool [mscorlib]System.String::op_Inequality(string,
string)
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: brfalse.s IL_0029
IL_0016: nop
IL_0017: ldstr "Error occured: {0}"
IL_001c: ldloc.0
IL_001d: call string [mscorlib]System.String::Format(string,
object)
IL_0022: call void [System]System.Diagnostics.Debug::WriteLine(string)
IL_0027: nop
IL_0028: nop
IL_0029: ret
} // end of method Program::Main

如您所见,Release 模式没有调用 Debug.WriteLine,而 Debug 模式调用。

关于c# - C# 编译器是否删除了封装 debug.writeline 的 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41143150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com