Python's memory management is based on reference counting and garbage collection mechanisms. 1. The reference counting mechanism ensures that objects are released immediately when the number of references is 0. The return value of sys.getrefcount() is 1 more than the actual reference because it increases its reference itself; 2. Circular references cannot be cleaned through reference counting, and it depends on the generational recycling of the gc module. Calling gc.collect() can recycle unreachable objects; 3. In actual development, long-term holding of large object references should be avoided. We can use weakref weak references, timely place None to release memory, and use tracemalloc to monitor memory allocation; 4. Summary: Python combines reference counting and garbage collection to manage memory. Developers can improve program efficiency through reasonable use of tools and optimized reference management. Although memory management is automatic, it needs to pay attention to the risks of circular references and memory leakage.
Python's memory management is mostly automated for developers, but understanding its underlying mechanisms can help write more efficient code. Here is a concrete example to illustrate how Python memory management works, including reference counting, garbage collection, and object lifecycle.

1. Example of reference counting mechanism
Python uses reference counts to track the usage of objects. When an object's reference count becomes 0, it is immediately released.
import sys # Create a list object a = [1, 2, 3] print(sys.getrefcount(a)) # Output: 2 (a and getrefcount parameters references) b = a print(sys.getrefcount(a)) # Output: 3 c = a print(sys.getrefcount(a)) # Output: 4 # Delete the reference del b print(sys.getrefcount(a)) # Output: 3 del c print(sys.getrefcount(a)) # Output: 2 del a # At this time, the reference count is 0 and the object is released
?? Note:
sys.getrefcount()
itself adds a reference, so the result is always 1 more than the actual one.
2. Recycling References and Garbage Collection (GC)
Reference counting cannot handle circular references, so Python's garbage collector (gc module) is needed.
import gc # Create a circular reference def create_cycle(): x = {} y = {} x['y'] = y y['x'] = x return x # Return the reference, but the internal loop reference z = create_cycle() # z points to a circular reference structure del z # Delete external references, but x and y still refer to each other# Manually trigger garbage collection collected = gc.collect() print(f"Retrieve {collected} objects") # Usually output 2 (two dictionaries)
In this example, even if no variables refer to these two dictionaries after del z
, they still cannot be released by reference counting because they refer to each other. Python's generational garbage collector detects and cleanses such unreachable objects.

3. Memory management tips (practical suggestions)
- Avoid unnecessary large object references : for example, when caching large amounts of data, consider using weak references (
weakref
). - Dereference large objects in time : Set to
None
after processing big data to help quickly release memory. - Monitor memory usage : You can use the
tracemalloc
module to track memory allocation.
import tracemalloc tracemalloc.start() # simulate memory allocation data = [i for i in range(10000)] current, peak = tracemalloc.get_traced_memory() print(f"Current memory usage: {current / 1024:.1f} KB") print(f"Peak Memory Usage: {peak / 1024:.1f} KB") tracemalloc.stop()
4. Summary of key points
- Python manages memory using the reference counting garbage collection mechanism.
- The object is released immediately when the reference count is 0.
- Recycling references require auxiliary cleaning of the GC module.
- Developers can optimize memory usage through tools such as
gc
andtracemalloc
.
Basically all this is not complicated but easy to ignore.
The above is the detailed content of python memory management example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

Use JUnit5 and Mockito to effectively isolate dependencies for unit testing. 1. Create a mock object through @Mock, @InjectMocks inject the tested instance, @ExtendWith enables Mockito extension; 2. Use when().thenReturn() to define the simulation behavior, verify() to verify the number of method calls and parameters; 3. Can simulate exception scenarios and verify error handling; 4. Recommend constructor injection, avoid over-simulation, and maintain test atomicity; 5. Use assertAll() to merge assertions, and @Nested organizes the test scenarios to improve test maintainability and reliability.

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

table-layout:fixed will force the table column width to be determined by the cell width of the first row to avoid the content affecting the layout. 1. Set table-layout:fixed and specify the table width; 2. Set the specific column width ratio for the first row th/td; 3. Use white-space:nowrap, overflow:hidden and text-overflow:ellipsis to control text overflow; 4. Applicable to background management, data reports and other scenarios that require stable layout and high-performance rendering, which can effectively prevent layout jitter and improve rendering efficiency.

json.loads() is used to parse JSON strings into Python data structures. 1. The input must be a string wrapped in double quotes and the boolean value is true/false; 2. Supports automatic conversion of null→None, object→dict, array→list, etc.; 3. It is often used to process JSON strings returned by API. For example, response_string can be directly accessed after parsing by json.loads(). When using it, you must ensure that the JSON format is correct, otherwise an exception will be thrown.

Choosetheappropriateindextypebasedonusecase,suchassinglefield,compound,multikey,text,geospatial,orTTLindexes.2.ApplytheESRrulewhencreatingcompoundindexesbyorderingfieldsasequality,sort,thenrange.3.Designindexestosupportcoveredqueriesbyincludingallque

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

VSCode portable mode can be implemented by downloading the ZIP version and correctly configuring it. 1. Download the Windows ZIP version and unzip it to the specified folder; 2. Create a data folder in the same level directory for storing configuration and extensions; 3. Create a batch script to set user-data-dir and extensions-dir to point to the data directory; 4. Run the script to start VSCode and verify that the settings and plug-ins are saved in data; after success, you can carry it with you, leaving no traces when used on different computers. Note that only Windows supports this mode and cannot use the installation version.
