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.
精彩评论