通常哪个更快,一个产量或一个附加? [英] Which is generally faster, a yield or an append?

查看:82
本文介绍了通常哪个更快,一个产量或一个附加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在一个个人学习项目中,在其中读取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.

通常更快一些:

  1. yield s或
  2. 函数中的
  3. 几个append(),然后是return,随后的list?
  1. yields, or
  2. several append()s within the function then return the ensuing list?

我很高兴知道在什么情况下yield会比append() s快,反之亦然.

I would be happy to know in what situations where yields 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比添加速度要快.

At least in this very simple test, yield is faster than append.

这篇关于通常哪个更快,一个产量或一个附加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆