【问题标题】:Which is more efficient coding: reusing variable vs writing same code twice?哪个更有效的编码:重用变量与两次编写相同的代码?
【发布时间】:2020-03-24 11:38:08
【问题描述】:

让我给你两个编码选项:

一)

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);

【问题讨论】:

  • 目前还没有可证明的实用角度来解决,因此可以将其标记为基于意见并关闭。实际上,您将来打算如何处理它,如果它只是一个平凡的功能并且浪费更多的时间而不是必要的时间,那么过度设计是没有意义的,这是过度设计的典型例子
  • “高效”是什么意思?

标签: c# variables error-handling coding-style


【解决方案1】:

应该直观地理解,两次调用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 

【讨论】:

    【解决方案2】:

    B) 在维护代码方面更“高效”,因为您只定义了一次字符串。

    它还调用String.Format 一次而不是两次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-21
      • 2011-04-04
      相关资源
      最近更新 更多