Which is generally faster, a yield or an append?(哪个通常更快,产量或附加?)
问题描述
我目前在一个个人学习项目中阅读 XML 数据库.我发现自己正在编写收集数据的函数,但我不确定返回它们的快速方法是什么.
I am currently in a personal learning project where I read in an XML database. I find myself writing functions that gather data and I'm not sure what would be a fast way to return them.
这通常更快:
yield
或- 函数中的几个
append()
然后return
随后的list
?
yield
s, or- several
append()
s within the function thenreturn
the ensuinglist
?
我很高兴知道在什么情况下 yield
s 会比 append()
s 更快,反之亦然.
I would be happy to know in what situations where yield
s would be faster than append()
s or vice-versa.
推荐答案
yield
具有惰性的巨大优势,而且速度通常不是最好的 使用它的理由.但是,如果它在您的上下文中有效,那么没有理由不使用它:
yield
has the huge advantage of being lazy and speed is usually not the best reason to use it. But if it works in your context, then there is no reason not to use it:
# yield_vs_append.py
data = range(1000)
def yielding():
def yielder():
for d in data:
yield d
return list(yielder())
def appending():
lst = []
for d in data:
lst.append(d)
return lst
这是结果:
python2.7 -m timeit -s "from yield_vs_append import yielding,appending" "yielding()"
10000 loops, best of 3: 80.1 usec per loop
python2.7 -m timeit -s "from yield_vs_append import yielding,appending" "appending()"
10000 loops, best of 3: 130 usec per loop
至少在这个非常简单的测试中,yield
比 append 快.
At least in this very simple test, yield
is faster than append.
这篇关于哪个通常更快,产量或附加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:哪个通常更快,产量或附加?


基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01