首页 > 解决方案 > 函数中间的函数声明会降低性能吗?

问题描述

我要问的例子:

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吗?

标签: python

解决方案


要扩展其中一条评论,您将在循环中添加额外的工作。每次您声明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

推荐阅读