我要问的例子:
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
的执行时间?
答案 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