Why we have to prefer generator instead of the other data object for yield-critical applications in python ?

First of all, when defined to variable in the source code, this variable come to life in source code's scope and it will run until the end of the program. Before the coding on project have to be well-planned for this situation. If it wouldn't be well-planned, every defined variable can leads to memory leakage problem. It's take risk for yield critical project. I will only explain what is important for memory useage.

Without noticing, i mentioned a yield keyword, it was suprised for me:) Yield keyword about the specific keyword on generator function. Low level programing languages when the use generator, its might be create static object on function. When the compiler look the this keyword, compiler would have to allocate the memory from random access memory(RAM). Actually static object which is the defined for generator in the function, you have to decide allocation(on the data structure) how to planned the code project.Lets demonstrate this topic;

Input :

def generator():    for i in range(0,1001):        if i % 2 == 0:            yield i

evanNumbers = [i for i in range(0,1001) if i % 2 == 0]

print("Evan Numbers size of List() = ", evanNumbers.__sizeof__())
print("Evan Numbers size of Generator() = ",generator.__sizeof__())

This example about uses the evan numbers. I will explain differences list() compare to generator() function. List keeping all values and take the memory in scope, but generator when using in statement, with this expression call construct destruct in generator's using line. So generator only use related line allocated memory, list(or another data object) more using the memory than generator. 

Output : 

Evan Numbers size of List() =  2124
Evan Numbers size of Generator() =  56


Comments