.NET 内存碎片的原因 [英] What causes memory fragmentation in .NET

查看:24
本文介绍了.NET 内存碎片的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Red Gates ANTS 内存分析器来调试内存泄漏.它不断警告我:

I am using Red Gates ANTS memory profiler to debug a memory leak. It keeps warning me that:

内存碎片可能导致.NET 来保留过多的可用内存.

Memory Fragmentation may be causing .NET to reserver too much free memory.

内存碎片影响可分配的最大对象的大小

Memory Fragmentation is affecting the size of the largest object that can be allocated

因为我有强迫症,这个问题必须解决.

Because I have OCD, this problem must be resolved.

有哪些有助于避免内存碎片的标准编码实践.你能通过一些 .NET 方法对其进行碎片整理吗?它甚至会有所帮助吗?

What are some standard coding practices that help avoid memory fragmentation. Can you defragment it through some .NET methods? Would it even help?

推荐答案

你知道,我有点怀疑这里的内存分析器..NET 中的内存管理系统实际上尝试通过移动内存来为您整理堆碎片(这就是为什么您需要固定内存以便与外部 DLL 共享).

You know, I somewhat doubt the memory profiler here. The memory management system in .NET actually tries to defragment the heap for you by moving around memory (that's why you need to pin memory for it to be shared with an external DLL).

在较长时间内进行的大内存分配容易产生更多碎片.虽然小的临时(短)内存请求不太可能导致 .NET 中的碎片.

Large memory allocations taken over longer periods of time is prone to more fragmentation. While small ephemeral (short) memory requests are unlikely to cause fragmentation in .NET.

这里也有一些值得思考的地方.对于 .NET 的当前 GC,分配的内存在时间上很近,通常在空间上间隔很近.这与碎片化相反.即您应该按照您打算访问它的方式分配内存.

Here's also something worth thinking about. With the current GC of .NET, memory allocated close in time, is typically spaced close together in space. Which is the opposite of fragmentation. i.e. You should allocate memory the way you intend to access it.

它是仅托管代码还是包含诸如 P/Invoke、非托管内存 (Marshal.AllocHGlobal) 或 GCHandle.Alloc(obj, GCHandleType.Pinned) 之类的内容?

Is it a managed code only or does it contains stuff like P/Invoke, unmanaged memory (Marshal.AllocHGlobal) or stuff like GCHandle.Alloc(obj, GCHandleType.Pinned)?

这篇关于.NET 内存碎片的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆