Memory Management in python is a less covered topic in most books but it is the most important topic. This topic also covers your all doubts about What is Mutable and Immutable Data types?.
So Let's Start exploring Memory management in Python:
For the sake of understanding, Let's compare python MM with C MM:
here, we can clearly see that we specify the data type that means memory size is pre-define for that specific variable.
For ex: float a=12.2 takes 4-byte space. So, We can clearly say that in C data stored in a specific size Memory block. and if you perform any change then the change will reflect in the same memory block.
For ex:
Memory Management in Python:
In Python instead of storing a value in a specific size block, here our variable refers to that memory block where value is stored.
here memory management is completely dynamic. As soon as you define a variable, it searches in memory that the value is already stored in memory or not.
if it is stored it start referring to that value:-
if it is not stored in any variable then it stores the value in a memory block and starts referring to that:-
Here If we update the Value of "a" then it cut reference from the prev memory location and start referring to a new memory block.
Advantages of Python's Dynamic MM
- We don't need to specify the data type of variable. Whatever value you store in a variable, it starts referring to that.
- you can assign any type of value to your variable because as soon as you change the value, it cut the reference from the prev memory location and start referring to the new one.
- We don't need to care about value size because python allows memory as per your value's requirement.
- Don't need to care about the garbage collector. As soon as no one referring to any memory block, the Garbage collector free of that memory location.
- if you store the same value in 2 or more variables, it will only take the same memory location for everyone. But there are two conditions-
- zero value is not stored in Python.
a. Variable should store INT value.
b. Value should be between -5 to 256.
-----------------------------------------------------------------------------------------------------------------------------
Well explained topic.
ReplyDelete