【问题标题】:C# if else vs if or vs switch case [duplicate]C# if else vs if or vs switch case [重复]
【发布时间】:2014-07-24 07:17:05
【问题描述】:

我试图让我的代码更快,我得到了很多 If-else 和 if-or 。我知道如果你有超过 5 个 if/case,switch case 会更快。那么if-elseif-or 的速度有多快,它们是一样的吗?

if (item.Datum.Substring(5, 5) == "06-20" || item.Datum.Substring(5, 5) == "06-21")
{
  Something
}
else if item.Datum.Substring(5, 5) == "06-22" || item.Datum.Substring(5, 5) == "06-23")
{
  Something
}

if (item.Datum.Substring(5, 5) == "06-20") 
{
  Something
}
else if (item.Datum.Substring(5, 5) == "06-21")
{
  Something
}
else if (item.Datum.Substring(5, 5) == "06-22")
{
  Something
}
else if (item.Datum.Substring(5, 5) == "06-23")
{
  Something
}

或者我应该只用开关盒吗?

switch(item.Datum.Substring(5, 5))
{
   case "06-20", "06,21":
      Something
      break;
   case "06-22", "06,23":
      Something
      break;
}

【问题讨论】:

  • 除此之外,不要给Substring打电话这么多次!
  • 如果你不每天调用这个函数百万次,我会认为它是过早的优化。我敢打赌,“Something”功能所花费的时间比您通过实施“案例”开关节省的时间要多得多。
  • 你分析过你的代码吗?这真的是其性能的瓶颈吗?如果是这样,您是否描述了替代方案?如果是这样,请选择您测量过以获得最佳性能的那个。

标签: c# if-statement case


【解决方案1】:

在某些情况下,等效的 switch 语句比 if 语句或 if 语句链慢。使用频率启发法,您可以在许多程序中使用 if 语句优化快速路径。

看到这个链接你会发现两个不同的比较

http://www.dotnetperls.com/if-switch-performance

【讨论】:

    【解决方案2】:

    当出现这样的问题时,我的哲学是:你写的越少越好。

    为什么会有这样的哲学?一个词:可测试性。
    每次添加一行时,都必须确保对其行为进行测试。我并不特别喜欢 switch 合成器,但是当它将行号除以 2 时,我接受它。

    【讨论】:

      【解决方案3】:

      我会去:

       dayStr = item.Datum.Substring(5, 5))
       day = 'split '-', ',' and convert to int'
       switch day:
       {
          case 20: // Fall through
          case 21:
             // Do something
      
          case 22:
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        • 2013-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多