在python中变量是否被分配给内容地址,如何在Python中为变量分配内存?

本文探讨了Python中浮点数类型的内存分配机制,指出内存大小并非静态确定,而是根据程序运行时的需求动态调整。重点讲解了Python的pymalloc内存管理系统如何处理大量小对象,以及float变量何时进行内存分配,特别提到了Python使用浮动池来管理float对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As an example, I have the following Python code:

>>> x = 9.89

Now I know the type will be determined as float dynamically during runtime, but I am unsure how memory is allocated. Would memory for the size of a float be allocated dynamically after the type is determined? Is the amount of memory allocated always the same?

解决方案Python does a lot of allocations and deallocations. All objects,

including "simple" types like integers and floats, are stored on the

heap. Calling malloc and free for each variable would be very slow.

Hence, the Python interpreter uses a variety of optimized memory

allocation schemes. The most important one is a malloc implementation

called pymalloc, designed specifically to handle large numbers of

small allocations. Any object that is smaller than 256 bytes uses this

allocator, while anything larger uses the system's malloc.

Memory allocation works at several levels in Python. There’s the

system’s own allocator, which is what shows up when you check the

memory use using the Windows Task Manager or ps. Then there’s the C

runtime’s memory allocator (malloc), which gets memory from the system

allocator, and hands it out in smaller chunks to the application.

Finally, there’s Python’s own object allocator, which is used for

objects up to 256 bytes. This allocator grabs large chunks of memory

from the C allocator, and chops them up in smaller pieces using an

algorithm carefully tuned for Python.

and specifically for floats:

floats also use an immortal & unbounded free list.

So no, it would only be allocated if there are no more free float spots in pythons free list, which depends on previous float usage in your program.

Ultimately, python is doing the memory management for you, so even a solid answer to your question won't give you much insight.

Additional discussion can be found at Python: garbage collection fails?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值