Memory management is very important during software development, to scale it in a healthy way, knowledge of its language functions must provide the performance that will make a difference.
Let's get to know generators in Python, what it is, how to use it and the relationship with memory management.
We can define generators as iterators, with the difference that the value is not stored, the execution occurs on the fly.
The best way to use is through functions, that you can get the value as the generation occur.
def generator_function():
for i in range(5):
yield i
# Output: 0
# 1
# 2
# 3
# 4
A good use is the fibonacci numbers, if we pass a function a like that...
def fibon(n):
a = b = 1
result = []
for i in range(n):
result.append(a)
a, b = b, a + b
return result
for x in fibon(1000000):
print(x)
We will probably run out of memory, because the result is being stored in a array.
With the generators...
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b
We will use far fewer resources because there is no value being stored.
This was just a simple example, but you had a view how the things work, the generators are powerful and a good friend of your system.
Top comments (0)