简体   繁体   English

性能注意事项在Python中使用多层生成器?

[英]Performance Considerations Using Multiple Layers of Generators in Python?

Are there any performance considerations for using a lot of generators chained together, as opposed to just a single generator. 使用大量链接在一起的发生器是否有任何性能考虑,而不是仅使用单个发生器。

For example: 例如:

def A(self, items):
    for item in self.AB(items):
        if object.A():
            yield item

def AB(self, items):
    for object in self.ABC(objects):
        if object.A() or object.B():
            yield object

def ABC(self, objects):
    for object in objects:
        if object.A() or object.B() or object.C():
            yield object

Clearly calling A(objects) is going to go through three different generators, but in many situations it makes the code re-use better if there are different generators to handle different filtering. 显然,调用A(objects)将经历三个不同的生成器,但在许多情况下,如果有不同的生成器来处理不同的过滤,它会使代码重用得更好。 Can anyone indicate that there is a significant impact on performance using this technique? 任何人都可以表明使用这种技术会对性能产生重大影响吗?

There is nothing wrong with chaining generators, but in this example there is no reason for A to call self.AB, it can just loop over items to get the same result. 链接生成器没有任何问题,但在此示例中,A没有理由调用self.AB,它可以循环遍历项目以获得相同的结果。

You should write your code as clearly as you can and if it's slow then use a profiler to determine where the bottleneck is. 您应该尽可能清楚地编写代码,如果速度慢,则使用分析器确定瓶颈的位置。 Contrived examples such as this one are too far from reality to be useful indicators of performance. 像这样的受控例子离现实太远,不能成为有用的绩效指标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM