开发者

In general, does replacing AND with a pair of nested IFs speed things up?

I'm weighing the differences between

If[condition1 AND condition2, A, B]

and

If[condition1, If[condition2, A, B], B]

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both p开发者_Python百科remises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.


Mathematica will short-circuit the evaluation of And and Or if the result becomes known before evaluating all the conditions.

You can see this by using a condition that (artificially) takes a long time:

Timing[If[False && (Pause[10]; True), True, False]]
Timing[If[False, If[(Pause[10]; True), True, False], False]]

and seeing that both return in a fraction of a second instead of in ten seconds.


Often (but not always), languages will have a feature called short circuited logic whereby the second operand in an AND condition will only be evaluated if the first is true (Also for an OR, the second will only be evaluated if the first is false). That would be dependent on the language, however.


I did some timing on

Nest[Defer@If[True, #] &, True, 300];

vs

If[True && << 298 >> && True, True];

which is total overkill but fun nonetheless. The nested If[] statements were three times slower than the If[] with 300 logical AND's. However, with the first True statement changed to False the tables are turned and the nested If[] statements are three times faster.


Are you asking about a specific language or just in general?

Many, but not all, languages have short circuit AND and ORoperators where they stop evaluation when they know the answer. For AND that means if the left side if false the answer is false and the right side does not need to be evaluated. For OR if the left side is true, then the answer is true and the rights side does not need to be evaluated.

For languages without short circute evaluation, you may get some speed improvement with nested ifs, because less work will have to be done. Whether that improvement is worth making the code harder to follow will depend on the situation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜