gpt4 book ai didi

c# - 哪种编码更有效: reusing variable vs writing same code twice?

转载 作者:行者123 更新时间:2023-12-03 09:07:55 25 4
gpt4 key购买 nike

让我给您2种编码方式:

一种)

Console.WriteLine(String.Format("Error: {0}", genericException.Message));
SomeTextFileLogMethod(String.Format("Error: {0}", genericException.Message));

B)
var errorMessage = "String.Format("Error: {0}", genericException.Message)";
Console.WriteLine(errorMessage);
SomeTextFileLogMethod(errorMessage);

最佳答案

从直觉上讲,两次调用String.Format将产生两倍的运营成本。在此演示中,您可以看到由代码生成的中间语言,与您正在执行的操作类似。您可以看到then ...之后完成了两次“工作”。区别是微小的。而且编译器可以进行不明显的优化,因此,如果对性能有合理的考虑,则始终建议进行基准测试。

如果您真的想编写有效的日志记录和消息传递代码,建议您使用为此设计的库。可以将Serilog之类的东西配置为写入多个“接收器”。因此,一个记录消息的调用可以转到控制台,文件,电子邮件,http端点等。

string msg = string.Format("Error: {0}", "test");

Console.WriteLine(msg);
Debug.WriteLine(msg);

Debug.Write("then...");

Console.WriteLine(string.Format("Error: {0}", "test"));
Debug.WriteLine(string.Format("Error: {0}", "test"));

IL_0000: nop
IL_0001: ldstr "Error: {0}"
IL_0006: ldstr "test"
IL_000B: call System.String.Format
IL_0010: stloc.0 // msg
IL_0011: ldloc.0 // msg
IL_0012: call System.Console.WriteLine
IL_0017: nop
IL_0018: ldloc.0 // msg
IL_0019: call System.Diagnostics.Debug.WriteLine
IL_001E: nop
IL_001F: ldstr "then..."
IL_0024: call System.Diagnostics.Debug.Write
IL_0029: nop
IL_002A: ldstr "Error: {0}"
IL_002F: ldstr "test"
IL_0034: call System.String.Format
IL_0039: call System.Console.WriteLine
IL_003E: nop
IL_003F: ldstr "Error: {0}"
IL_0044: ldstr "test"
IL_0049: call System.String.Format
IL_004E: call System.Diagnostics.Debug.WriteLine
IL_0053: nop
IL_0054: ret

关于c# - 哪种编码更有效: reusing variable vs writing same code twice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60830281/

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