gpt4 book ai didi

memory-management - C/Pascal 的堆管理器,可自动用零字节填充已释放的内存

转载 作者:行者123 更新时间:2023-12-04 22:18:50 24 4
gpt4 key购买 nike

您如何看待用零字节填充已释放(未实际使用)页面的选项?这可能会提高 Windows 下的性能,也可以提高 VMWare 和其他虚拟机环境下的性能?例如,VMWare 和 HyperV 计算内存页的哈希值,如果内容相同,则将此页标记为“共享”在虚拟机内部以及同一主机上的虚拟机之间,直到页面被修改。它有效地减少了内存消耗。 Windows 也是如此——它以不同的方式处理零页,将它们视为免费的。

我们可以让堆管理器在调用 FreeMem/ReallocMem 时自动用零填充内存。作为另一种选择,我们可以有一个函数根据需要将空内存归零,即仅当该函数被显式调用时。当然,这个函数必须是线程安全的。
用零填充内存的缺点是触及可能已经变成虚拟的内存,从而导致页面错误。除此之外,任何内存存储操作都很慢,所以我们的程序会更慢,尽管程度未知(可能可以忽略不计)。

如果我们设法用零完全填充 4-K 页,虚拟机管理程序或 Windows 会明确地将其标记为零页。但即使是部分清零也可能是有益的,因为管理程序可能会使用 LZ 或类似算法来压缩页面以节省物理内存。

我只是想知道您的意见,堆管理器本身用零字节填充空堆内存的好处是否会超过这种技术的缺点。

当我们购买减少的物理内存消耗时,归零是否值得付出代价?

最佳答案

当您不再关心某个页面的内容但仍希望保持分配状态时,您可以调用 VirtualAlloc(和变体)并传递 MEM_RESET 标志。

来自 VirtualAlloc on MSDN :

MEM_RESET

Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This value cannot be used with any other value.

Using this value does not guarantee that the range operated on with MEM_RESET will contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it.



这提供了两全其美的方法 - 您没有将内存归零的成本,并且系统没有将其重新调入的成本。您可以利用经过良好调整的内存管理器零池。

类似的功能也存在于 Linux 上的 MADV_FREE (或 MADV_DONTNEED for Posix)标志下到 madviseGlibc uses this function in the implementation of its heap. :
/* 
* Stack:
* int shrink_heap (heap_info *h, long diff)
* int heap_trim (heap_info *heap, size_t pad) at arena.c:660
* void _int_free (mstate av, mchunkptr p, int have_lock) at malloc.c:4097
* void __libc_free (void *mem) at malloc.c:2948
* void free(void *mem)
*/

static int
shrink_heap (heap_info *h, long diff)
{
long new_size;

new_size = (long) h->size - diff;
/* ... snip ... */

__madvise ((char *) h + new_size, diff, MADV_DONTNEED);

/* ... snip ... */
h->size = new_size;
return 0;
}

关于memory-management - C/Pascal 的堆管理器,可自动用零字节填充已释放的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44665446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com