Case vs If Else If:哪个更有效? [英] Case vs If Else If: Which is more efficient?

查看:38
本文介绍了Case vs If Else If:哪个更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
是否则如果"比switch() case"更快?
if/的相对性能如何?其他与 Java 中的 switch 相比?

我再次在运行中编码......当调试器单步执行 case 语句时,它会立即跳转到与条件匹配的项目,但是当使用 if/else 指定相同的逻辑时,它会单步执行每个 if 语句,直到找到获胜者.case 语句是更有效,还是我的调试器只是优化了单步执行?(不要担心语法/错误,我在 SO 中输入了这个,不知道它是否会编译,这是我追求的原则,我不想将它们作为整数,因为我依稀记得一些关于使用带有整数的偏移量的情况)我使用 C#,但我对跨编程语言的一般答案感兴趣.

Ive been coding-in-the-run again....when the debugger steps through a case statement it jumps to the item that matches the conditions immediately, however when the same logic is specified using if/else it steps through every if statement until it finds the winner. Is the case statement more efficient, or is my debugger just optimizing the step through? (don't worry about the syntax/errors, i typed this in SO, don't know if it will compile, its the principle i'm after, I didn't want to do them as ints cause i vaguely remember something about case using an offset with ints) I use C#, but im interested in a general answer across programming languages.

switch(myObject.GetType()){

    case typeof(Car):
        //do something
        break;

    case typeof(Bike):
        //do something
        break;

    case typeof(Unicycle):
        //do something
        break;

    case default:
        break;
}

VS

   Type myType = myObject.GetType();

   if (myType == typeof(Car)){
            //do something
   }

   else if (myType == typeof(Bike)){
            //do something
   }

   else if (myType == typeof(Unicycle)){
            //do something
   }
   else{

   }

推荐答案

似乎编译器在优化 switch 语句方面比 if 语句更好.

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

编译器不知道评估 if 语句的顺序对您是否重要,并且无法在那里执行任何优化.您可能会在 if 语句中调用方法,从而影响变量.使用 switch 语句,它知道可以同时评估所有子句,并且可以将它们按最有效的顺序排列.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

这是一个小的比较:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

这篇关于Case vs If Else If:哪个更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆