开发者

Cheap() && Expensive()

开发者 https://www.devze.com 2023-03-27 17:27 出处:网络
This comment was made on a question i asked about optimisation. \"Note that cheap() && expensive() is not an optimisation of expensive () && cheap() in a language with short-circuit ev

This comment was made on a question i asked about optimisation. "Note that cheap() && expensive() is not an optimisation of expensive () && cheap() in a language with short-circuit evaluation unless you can guarantee that both expensive() and cheap() are side effect free"

w开发者_Go百科hat does this mean?


Due to short circuit evaluation, when the expression expensive () && cheap() runs, cheap() will only run if expensive() returns true. In the case where both methods are side effect free, which means they are just returning a boolean and not making any changes application state, then the expressions can be reversed to cheap() && expensive(), which will be faster assuming cheap() is not always true.

However, in the case where either method modifies the state of the application then the reversed expression may not be functionally equivalent.


If cheap() and/or expensive() can have side effects, then in a language with short-circuiting AND, changing the order can change the semantics of the program, I.e., you get a different answer just by changing the order.

0

精彩评论

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