这些陈述是否正确?
>每次引用计数变为零时,分配的空间将添加到“可用”列表中.
>对于下一次分配,使用最适合大小的最前面的内存块.
>将尽可能再次使用先前耗尽的内存块
“可用列表”是否按地址位置或大小排序?
是否会活动物体以便更好地压实?
我在编译Swift程序的程序集中进行了一些挖掘,并且我发现swift:: swift_allocObject
是在实例化新的Class对象时调用的运行时函数.它调用
SWIFT_RT_ENTRY_IMPL(swift_allocObject)
调用
swift::swift_slowAlloc
,最终从C标准库调用… malloc().所以Swift的运行时没有进行内存分配,它就是malloc().
malloc()在C库(libc)中实现.您可以看到Apple的libc 0700实现.在/gen/malloc.c
中定义了malloc().如果您对使用的内存分配算法感兴趣,可以继续沿着兔子洞的行程
那里.
Is the ‘available list’ sorted by address location or size?
这是malloc的一个实现细节,我欢迎您在上面链接的源代码中发现.
1. Every time a reference count becomes zero, the allocated space gets added to an ‘available’ list.
对,那是正确的.除“可用”列表可能不是列表.此外,此操作不一定由Swift运行时库完成,但可以由OS内核通过系统调用完成.
2. For the next allocation, the frontmost chunk of memory which can fit the size is used.
不一定是最重要的.有许多不同的内存分配方案.你想到的那个被称为“第一次适合”.以下是一些示例内存分配技术(从this site开始):
Best fit: The allocator places a process in the smallest block of unallocated memory in which it will fit. For example, suppose a process requests 12KB of memory and the memory manager currently has a list of unallocated blocks of 6KB, 14KB, 19KB, 11KB, and 13KB blocks. The best-fit strategy will allocate 12KB of the 13KB block to the process.
First fit: There may be many holes in the memory, so the operating system, to reduce the amount of time it spends analyzing the available spaces, begins at the start of primary memory and allocates memory from the first hole it encounters large enough to satisfy the request. Using the same example as above, first fit will allocate 12KB of the 14KB block to the process.
- Worst fit: The memory manager places a process in the largest block of unallocated memory available. The idea is that this placement will create the largest hold after the allocations, thus increasing the possibility that, compared to best fit, another process can use the remaining space. Using the same example as above, worst fit will allocate 12KB of the 19KB block to the process, leaving a 7KB block for future use.
对象在其生命周期内不会被压缩. libc通过分配内存的方式处理内存碎片.它无法移动已经分配的对象.