python - Python 有堆栈/堆吗?内存是如何管理的?

标签 python memory memory-management

如何在 Python 中管理变量和内存?它有堆栈和堆吗?用什么算法来管理内存?鉴于这些知识,对于大量/数据处理的内存管理有什么建议吗?

最佳答案

How are variables and memory managed in Python.

自动神奇!不,实际上,您只需创建一个对象,Python 虚拟机就会处理所需的内存以及将其放置在内存布局中的位置。

Does it have a stack and a heap and what algorithm is used to manage memory?

当我们谈论 CPython 时,它使用私有(private)堆 来存储对象。 From the CPython C API documentation :

Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.

内存回收主要由引用计数处理。也就是说,Python VM 保留一个内部日志,记录有多少引用引用了一个对象,并在没有更多引用引用它时自动对其进行垃圾回收。此外,还有a mechanism to break circular references (引用计数无法处理)通过检测无法到达的对象“孤岛”,somewhat in reverse of traditional GC algorithms试图找到所有可达的对象。

注意:请记住,此信息是 CPython 特定的。其他 python 实现,例如 pypyiron pythonjython 等在实现细节方面可能彼此不同,也可能与 CPython 不同.为了更好地理解这一点,理解 Python 语义(语言)和底层实现之间存在差异可能会有所帮助

Given this knowledge are there any recommendations on memory management for large number/data crunching?

现在我不能谈论这个,但我确信NumPy (最流行的数字运算 python 库)具有优雅地处理内存消耗的机制。

如果您想了解更多关于 Python 的内部机制,请查看这些资源:

关于python - Python 有堆栈/堆吗?内存是如何管理的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56788703/

相关文章:

C数据结构到磁盘

javascript - 复制数组的内存有效方法

c - 什么时候函数会加载到内存中?

c++ - 探索内存管理器

c++ - 我应该使用什么 C++ STL 类来减少由大量小分配引起的碎片?

python - SQLite 返回日期超过一周的记录

python - 如何使用迭代函数按最小值排序?

android - 如何清除文本编辑字段?安卓 python appium

python - 在 Python 中 Hook str.__getitem__

c - 最佳缓冲区大小