开发者

Boolean functions: if statements or simple return

I was checking a friend's code, and this pattern showed up quite a bit whenever he wrote functions that retu开发者_如何学Pythonrned a boolean value:

def multiple_of_three(n):
    if (n % 3) is 0:
       return True
    else:
       return False

I maintain that it's simpler (and perhaps a bit faster) to write:

def multiple_of_three(n):
    return (n % 3) is 0

Am I correct that the second implementation is faster? Also, is it any less readable or somehow frowned upon?


I very much doubt there is a compiler or interpreter still out there where there is a significant speed difference - most will generate exactly the same code in both situations. But your "direct return" method is, in my opinion, clearer and more maintainable.


I can't speak of the Python interpreter's exact behavior, but doing one way over another like that (in any language) simply for reasons of "faster" is misguided, and qualifies as "premature optimization". As Paul Tomblin stated in another answer, the difference in speed, if any, is quite negligible. Common practice does dictate, however, that the second form in this case is more readable. If an expression is implicitly boolean, then the if statement wrapper is frivolous.

See also http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize


The second form is the preferred form. In my experience the first form is usually the sign of an inexperienced programmer (and this does not apply solely to Python - this crops up in most languages).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜