Why does removing the else slow down my code?

前端 未结 3 1376
清歌不尽
清歌不尽 2021-02-02 10:48

Consider the following functions:

def fact1(n):
    if n < 2:
        return 1
    else:
        return n * fact1(n-1)

def fact2(n):
    if n < 2:
                


        
3条回答
  •  隐瞒了意图╮
    2021-02-02 11:21

    What is happening here is that fact2 has a hash conflict with __name__ in your module globals. That makes the lookup of the global fact2 ever so slightly slower.

    >>> [(k, hash(k) % 32) for k in globals().keys() ]
    [('__builtins__', 8), ('__package__', 15), ('fact2', 25), ('__name__', 25), ('fact1', 26), ('__doc__', 29)]
    

    i.e. The same answer as for Why is early return slower than else? except that there the hash conflict was with __builtins__

提交回复
热议问题