Python 简明教程
Python - Memory Management
在 Python 中, memory management 是自动的,它涉及处理包含所有 Python 对象和 data structures 的私有堆。Python 内存管理器在内部确保该内存的有效分配和释放。本教程将探讨 Python 的内存管理机制,包括垃圾回收、引用计数以及变量在堆栈和堆中存储的方式。
In Python, memory management is automatic, it involves handling a private heap that contains all Python objects and data structures. The Python memory manager internally ensures the efficient allocation and deallocation of this memory. This tutorial will explore Python’s memory management mechanisms, including garbage collection, reference counting, and how variables are stored on the stack and heap.
Memory Management Components
Python 的内存管理组件在整个 Python 程序执行过程中都能提供高效有效的内存资源利用。Python 具有三个内存管理组件 −
Python’s memory management components provides efficient and effective utilization of memory resources throughout the execution of Python programs. Python has three memory management components −
-
Private Heap: Acts as the main storage for all Python objects and data. It is managed internally by the Python memory manager.
-
Raw Memory Allocator: This low-level component directly interacts with the operating system to reserve memory space in Python’s private heap. It ensures there’s enough room for Python’s data structures and objects.
-
Object-Specific Allocators: On top of the raw memory allocator, several object-specific allocators manage memory for different types of objects, such as integers, strings, tuples, and dictionaries.
Memory Allocation in Python
Python 以两种主要方式管理内存分配 − 堆栈和堆。
Python manages memory allocation in two primary ways − Stack and Heap.
Stack − Static Memory Allocation
在静态内存分配中,内存是在编译时分配并在堆栈中存储。这对于函数调用堆栈和变量引用来说是典型的。堆栈是用于存储本地变量和函数调用信息的内存区域。它基于后进先出 (LIFO) 原则运行,其中最近添加的项目将第一个被移除。
In static memory allocation, memory is allocated at compile time and stored in the stack. This is typical for function call stacks and variable references. The stack is a region of memory used for storing local variables and function call information. It operates on a Last-In-First-Out (LIFO) basis, where the most recently added item is the first to be removed.
堆栈通常用于存储基本数据类型的变量,例如数字、布尔值和字符。这些变量具有固定的内存大小,在编译时已知。
The stack is generally used for variables of primitive data types, such as numbers, booleans, and characters. These variables have a fixed memory size, which is known at compile-time.
Example
让我们看一个示例来说明基本类型变量如何在堆栈中存储。在上面的示例中,名为 x、y 和 z 的变量是名为 example_function() 的函数内的局部变量。它们存储在堆栈中,当函数执行完成时,它们会自动从堆栈中移除。
Let us look at an example to illustrate how variables of primitive types are stored on the stack. In the above example, variables named x, y, and z are local variables within the function named example_function(). They are stored on the stack, and when the function execution completes, they are automatically removed from the stack.
def my_function():
x = 5
y = True
z = 'Hello'
return x, y, z
print(my_function())
print(x, y, z)
执行上述程序时,您将获得以下 output −
On executing the above program, you will get the following output −
(5, True, 'Hello')
Traceback (most recent call last):
File "/home/cg/root/71937/main.py", line 8, in <module>
print(x, y, z)
NameError: name 'x' is not defined
Heap − Dynamic Memory Allocation
动态内存分配是在运行时为非基本类型对象和数据结构进行的。这些对象的实际数据存储在堆中,而对其进行引用的存储在堆栈中。
Dynamic memory allocation occurs at runtime for objects and data structures of non-primitive types. The actual data of these objects is stored in the heap, while references to them are stored on the stack.
Example
让我们观察一个示例,用于动态分配堆中内存的列表创建。
Let’s observe an example for creating a list dynamically allocates memory in the heap.
a = [0]*10
print(a)
Output
通过执行以上的程序,你会得到以下结果:
On executing the above program, you will get the following results −
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Garbage Collection in Python
Python 中的垃圾回收是自动释放不再用作对象的内存并使其可用于其他对象的过程。Python 垃圾回收器在程序执行期间运行并在对象的 reference count 降至零时激活。
Garbage Collection in Python is the process of automatically freeing up memory that is no longer in use by objects, making it available for other objects. Python’s garbage collector runs during program execution and activates when an object’s reference count drops to zero.
Reference Counting
Python 的主要垃圾回收机制是引用计数。Python 中的每个对象都维持一个引用计数,该引用计数追踪有多少别名(或引用)指向它。当对象的引用计数降至零时,垃圾回收器解除该对象的分配。
Python’s primary garbage collection mechanism is reference counting. Every object in Python maintains a reference count that tracks how many aliases (or references) point to it. When an object’s reference count drops to zero, the garbage collector deallocates the object.
引用计数的原理如下:
Working of the reference counting as follows −
-
Increasing Reference Count− It happens when a new reference to an object is created, the reference count increases.
-
Decreasing Reference Count− When a reference to an object is removed or goes out of scope, the reference count decreases.
Example
下面是演示 Python 中引用计数如何工作的一个示例。
Here is an example that demonstrates working of reference counting in Python.
import sys
# Create a string object
name = "Tutorialspoint"
print("Initial reference count:", sys.getrefcount(name))
# Assign the same string to another variable
other_name = "Tutorialspoint"
print("Reference count after assignment:", sys.getrefcount(name))
# Concatenate the string with another string
string_sum = name + ' Python'
print("Reference count after concatenation:", sys.getrefcount(name))
# Put the name inside a list multiple times
list_of_names = [name, name, name]
print("Reference count after creating a list with 'name' 3 times:", sys.getrefcount(name))
# Deleting one more reference to 'name'
del other_name
print("Reference count after deleting 'other_name':", sys.getrefcount(name))
# Deleting the list reference
del list_of_names
print("Reference count after deleting the list:", sys.getrefcount(name))
Output
通过执行以上的程序,你会得到以下结果:
On executing the above program, you will get the following results −
Initial reference count: 4
Reference count after assignment: 5
Reference count after concatenation: 5
Reference count after creating a list with 'name' 3 times: 8
Reference count after deleting 'other_name': 7
Reference count after deleting the list: 4