更快的是什么:如果是,还是如果? [英] What is faster: many ifs, or else if?

查看:109
本文介绍了更快的是什么:如果是,还是如果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历数组,并按值将其排序为一周中的几天.

I'm iterating through an array and sorting it by values into days of the week.

为了做到这一点,我使用了许多if语句.如果我使用许多if而不是一组else if语句,对处理速度有什么影响?

In order to do it I'm using many if statements. Does it make any difference to the processing speed if I use many ifs, versus a set of else if statements?

推荐答案

是的,如果使用其他代码,请考虑以下代码:

Yes, use an else if, consider the following code:

if(predicateA){
  //do Stuff
}
if(predicateB){
  // do more stuff
}

if(predicateA){
  //
}
else if(predicateB){
  //
}

在第二种情况下,如果谓词A为true,则不需要对谓词B(以及任何其他谓词)进行求值(因此,整个代码将更快地执行),而在第一个示例中,如果谓词A为true,则谓词B仍将始终如果谓词A和谓词B不互斥,您可能还会得到一些意想不到的惊喜.

in the second case if predicateA is true, predicateB (and any further predicates) will not need to be evaluated (and so the whole code will execute faster), whereas in the first example if predicateA is true, predicateB will still always be evaluated, and you may also get some unexpected suprises if predicateA and predicateB are not mutually exclusive.

这篇关于更快的是什么:如果是,还是如果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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