Home  >  Article  >  Backend Development  >  Memory management in Python

Memory management in Python

WBOY
WBOYforward
2023-09-10 21:33:031512browse

Memory management in Python

Writing code that is memory efficient and fast in execution is what every developer wants when working with any programming language. In Python, memory allocation and deallocation is not manual because Python has a garbage collector.

Now, what is a garbage collector.

Garbage Collector

Garbage collection refers to how memory is released when it is not in use and how it is made available for use by other objects. Python deletes objects that are no longer used. This is what we call garbage collection. The garbage collector starts the execution of the program and is activated when the reference count drops to zero.

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases pointing to it changes.

Now let’s see how memory is allocated in Python -

Static Memory Allocation - Stack

In static memory allocation, memory is allocated at compile time. Stack data structure stores static memory.

A simple example of allocating memory on the stack -

static int x=2;

Dynamic memory allocation – heap

In dynamic memory allocation, memory is allocated at runtime. The heap stores dynamic memory. If the object is no longer needed, it frees the memory space.

A simple example where memory is allocated on the heap for 2 integers -

x = [0]*2

As we discussed above, the garbage collector starts its execution with the program and is activated when the reference count drops to zero. Let's see what reference counting is.

Reference Count

The Python garbage collector starts the execution of a program and is activated when the reference count drops to zero. Let's see when the reference count increases or decreases

When the reference count value increases -

  • The reference count increments its value when a new name is assigned or assigned in a dictionary or tuple.

  • If we reallocate the reference to the object, the reference count decreases its value.

When the reference count decreases -

  • When the reference to the object goes out of scope, this value will be reduced.
  • This value is decreased when the object is deleted.

Therefore, the reference count is actually the number of times that other objects refer to an object. This way, deallocation occurs when the reference count drops to zero.

The above is the detailed content of Memory management in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete