Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Can anyone indicate that there is a significant impact on performance using this technique?

like image 985
Dan Avatar asked May 17 '26 20:05

Dan


1 Answers

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.

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.

like image 105
Andrew Wilkinson Avatar answered May 19 '26 11:05

Andrew Wilkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!