函数中间的函数声明会降低性能吗?

时间:2019-01-07 03:00:31

标签: python

我要问的例子:

def foo(bar):
    """Do a print function bar times"""
    count = 0
    while count < bar:
        def baz():
            return "This is baz"
        print(baz())
        count += 1

while循环中间的函数声明是否会减慢foo的执行时间?

1 个答案:

答案 0 :(得分:2)

要扩展其中一个注释,请向循环中添加其他工作。每次您声明baz()时,编译过程都在进行工作并分配内存。您是否有任何特定原因想要这样做?

更有效的代码:

def foo(bar):
    """Do a print function bar times"""
    count = 0
    def baz():
       return "This is baz"
    while count < bar:
        print(baz())
        count += 1

最有效的代码:

def baz():
    return "This is baz"
def foo(bar):
    """Do a print function bar times"""
    count = 0
    while count < bar:
        print(baz())
        count += 1