What causes memory fragmentation in .NET.

I am using the ANTS Red Gates memory profiler to debug a memory leak. He warns me that:

Memory fragmentation can cause .NET to reserve too much free memory.

or

Memory fragmentation affects the size of the largest object that can be allocated

Since I have OCD, this problem should be resolved.

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

+42
memory-management c # memory-leaks fragmentation
Mar 09 2018-11-11T00:
source share
3 answers

You know, I have some doubts about the memory profiler here. The memory management system in .NET is actually trying to defragment the heap for you while navigating through memory (so you need to attach memory for sharing with an external DLL).

Larger memory allocations taken over longer periods of time are subject to greater fragmentation. Although small ephemeral (short) memory requests are unlikely to cause fragmentation in .NET.

It is also worth considering. With the current GC.NET, memory allocated close in time is usually located at a distance from each other in space. Which is the opposite of fragmentation. those. you must allocate memory the way you want to access it.

Is it just managed code or does it contain things like P / Invoke, unmanaged memory (Marshal.AllocHGlobal), or something like GCHandle.Alloc (obj, GCHandleType.Pinned)?

+9
Mar 09 '11 at 9:12
source share

The GC heap handles large object distributions differently. It does not compress them, but simply combines adjacent free blocks (for example, traditional unmanaged memory storage).

Additional information here: http://msdn.microsoft.com/en-us/magazine/cc534993.aspx

So the best strategy with very large objects is to select them once and then hold them and reuse them.

+10
Mar 09 '11 at 9:22
source share

The .NET Framework 4.5.1 has the ability to explicitly compact a bunch of large objects (LOH) during garbage collection.

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); 

See more information in GCSettings.LargeObjectHeapCompactionMode

+6
Jan 02 '15 at 7:17
source share



All Articles