📜 ⬆️ ⬇️

Generators vs classes

A very small post about what to choose: a generator or class, when implementation is possible in both ways.

Not a difficult choice


Simple task: to calculate the moving average. The initial implementation was in the form of a class, but the presence of generators, which somehow fit the concept, did not give rest. But a simple test helped make a choice.

class EMA(object): def __init__(self, alpha=0.5): self.value = 0 self.alpha = alpha def update(self, price): self.value = self.value + self.alpha * (price - self.value) def ema(alpha=0.5): result = 0 previous = (yield) while True: price = (yield result) result = result + alpha(price - result) 

Now we carry out 2 measurements: we create a million generators and a million classes, examine time and memory:
ImplementationMemoryTime
Generators433,012 MB0: 00: 02.330000
Classes200,504 MB0: 00: 01.807000

Conclusion: Python classes are very lightweight. Use them boldly.

PS Under the debugger, classes were created for more than 6 seconds, and the creation time of the generators increased by just 1 second. Do not measure under the debugger.

')

Source: https://habr.com/ru/post/150798/


All Articles