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
吗?
解决方案
要扩展其中一条评论,您将在循环中添加额外的工作。每次您声明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
推荐阅读
- c++ - 为什么我收到链接器错误:未定义对...的引用?
- node.js - Node.js 后端/服务器:在“新函数”实例中无法“要求”
- python - 在 python 函数中执行 bash 命令行
- python - 为什么我在 Python 上使用 BackTrader 会收到此错误?
- spring-mvc - 如何使用 ResponseEntity 从我的 REST 调用中返回简单的错误消息?
- javascript - Angular 的订阅未记录完整错误
- python - keras,无效的预测大小
- java - 如何使 Spring Projections 与 @OneToOne 关系一起工作?
- react-native - 使用 React Navigation 防止在选项卡更改时重新渲染
- r - 在 R 中绘制 geom_line 和 geom_ribbon 时如何添加不连续性?