主页 > 软件教程

switch和if else 哪个效率高(C#多分支效率比较)

软件教程 2024-01-09

在 C# 中,多分支语句有两种,一种是 if elseif,另一种是 switch。在编程过程中,该用哪一种,应该根据具体情况和程序的执行效率决定。本文将探讨 switch 和 if elseif 倒底哪个效率高,下面是具体分析。

先看两种语句实现的代码:

//页面初始化
  protected void Page_Load(object sender, EventArgs e)
  {
    If_Elseif(3);
    Switch_Case(3);
  }

//测试 if elseif
  public string If_Elseif(int n)
  {
    string returnValue = "亮术网";

  Stopwatch sw = new Stopwatch();
    sw.Start();

  for (int i = 0; i < 10000000; i++)
    {
      if (n == 1)
        returnValue = "网页打不开";
      else if (n == 2)
        returnValue = "网页打开慢";
      else if (n == 3)
        returnValue = "网页显示不正常";
      else if (n == 4)
        returnValue = "网页显示乱码";
      else if (n == 5)
        returnValue = "Ie网页打不开";
      else if (n == 6)
        returnValue = "Chrome网页打不开";
    }
    sw.Stop();
    lblRunTime.Text = " If_Elseif: " + sw.ElapsedMilliseconds;//label 标签
    return returnValue;
  }

//测试 Switch case
  public string Switch_Case(int n)
  {
    string returnValue = "亮术网";

  Stopwatch sw = new Stopwatch();
    sw.Start();

  for (int i = 0; i < 10000000; i++)
    {
      switch (n)
      {
        case 1:
          returnValue = "网页打不开";
          break;
        case 2:
          returnValue = "网页打开慢";
          break;
        case 3:
          returnValue = "网页显示不正常";
          break;
        case 4:
          returnValue = "网页显示乱码";
          break;
        case 5:
          returnValue = "Ie网页打不开";
          break;
        case 6:
          returnValue = "Chrome网页打不开";
          break;
        default:
          break;
      }
    }
    sw.Stop();
    lblRunTime.Text += "ms Switch_Case: " + sw.ElapsedMilliseconds + "ms";
    return returnValue;
  }

运行结果:

If_Elseif: 162ms Switch_Case: 71ms

从运行结果可以看出,if elseif 用的时间比 Switch 多出91ms,程序循环了10000000次。如果循环次数继续增加,Switch 的效率更为明显,可见 Switch 的效率比 if> elseif 要高。

switch 之所以快,是因为编译后 switc 增加了一个索引跳转,而 if ... elseif 没有增加索引跳转。看反编译后的 ildasm 代码,可以发现 Switch_Case 方法中增加了下面这一句:

switch (IL_003f, IL_0047, IL_004f, IL_0057, IL_005f, IL_0067)

正是它实现了一个 jump table。  


标签: C#多分支效率比较

电脑软硬件教程网 Copyright © 2016-2030 www.computer26.com. Some Rights Reserved.