Why does removing the else slow down my code?

前端 未结 3 1382
清歌不尽
清歌不尽 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:15

    I question the timings. The two functions aren't recursing to themselves. fact1 and fact2 both call fact which isn't shown.

    Once that is fixed, the disassembly (in both Py2.6 and Py2.7) shows that both are running the same op codes except for the name of the recursed into function. The choice of name trigger a small difference in timings because fact1 may insert in the module dictionary with no name collisions while *fact2) may have a hash value that collides with another name in the module.

    In other words, any differences you see in timings are not due to the choice of whether the else-clause is present :-)

提交回复
热议问题