如何避免Swift中的内存碎片

如何避免Swift中的内存碎片,第1张

概述GC的压缩,扫描和标记可以避免堆内存碎片.那么 Swift中如何避免内存碎片? 这些陈述是否正确? >每次引用计数变为零时,分配的空间将添加到“可用”列表中. >对于下一次分配,使用最适合大小的最前面的内存块. >将尽可能再次使用先前耗尽的内存块 “可用列表”是否按地址位置或大小排序? 是否会活动物体以便更好地压实? 我在编译Swift程序的程序集中进行了一些挖掘,并且我发现 swift:: sw GC的压缩,扫描和标记可以避免堆内存碎片.那么 Swift中如何避免内存碎片?

这些陈述是否正确?

>每次引用计数变为零时,分配的空间将添加到“可用”列表中.
>对于下一次分配,使用最适合大小的最前面的内存块.
>将尽可能再次使用先前耗尽的内存块

“可用列表”是否按地址位置或大小排序?

是否会活动物体以便更好地压实?

解决方法 我在编译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通过分配内存的方式处理内存碎片.它无法移动已经分配的对象.

总结

以上是内存溢出为你收集整理的如何避免Swift中的内存碎片全部内容,希望文章能够帮你解决如何避免Swift中的内存碎片所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1005649.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存