案例与其他案例如果:哪个更有效率? [英] Case vs If Else If: Which is more efficient?

查看:98
本文介绍了案例与其他案例如果:哪个更有效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否则如果”快于'switch()案例” ?

Java中if / else与switch的相对性能是什么?

我已经在运行中进行编码....当调试器逐步执行case语句时,它会立即跳转到与条件匹配的项,但是当使用if / else指定相同的逻辑时通过每个if语句直到找到胜利者。 case语句是否更有效,或者我的调试器只是优化了一步? (不要担心语法/错误,我在SO中键入它,不知道它是否会编译,它的原理我之后,我不想做它们作为int因为我依稀记得一些关于使用带有整数的偏移的情况)我使用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

这篇关于案例与其他案例如果:哪个更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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