C# if else vs if 或 vs switch case

标签 c# if-statement case

<分区>

我试图使我的代码更快并且我在其中得到了很多 If-else 和 if-or。我知道如果 if/case 超过 5 个,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 case 吗?

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

最佳答案

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

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

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

关于C# if else vs if 或 vs switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24927331/

相关文章:

MySQL IF 触发错误

c - C编译出错?

带有 case 语句的 Mysql SUM

mysql - 如何在mysql中使用 'select'中的 'case when then'?

C# 测试 null

c# - 基于 C# 中的 DropDownList 在 Asp.net Gridview 中启用禁用复选框

c# - Session中存储的数据有多安全

python - JUMP_FORWARD 或 JUMP_ABSOLUTE 与 IF 语句? Python 2.5

mysql - CASE..WHEN 中的所有子查询是否都被执行,即使只满足一个条件?

c# - 在 C# 中使用文件的 TransactionScope