Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you give me an example that causes memory fragmentation in .NET

Tags:

c#

.net

memory

I'm working to make our application more performant by caching more stuff in memory. What worries me, though, is all that I'm reading about how the large object heap is not really compacted during a garbage collection, and that this can cause memory fragmentation.

I've been doing some small testing, but it seems I can't induce this problem. So here's my question: Can you show me a code snippet in C# that would, at some point, cause failure due to memory fragmentation?

like image 764
Dave Van den Eynde Avatar asked Nov 03 '22 17:11

Dave Van den Eynde


1 Answers

Try having a look at the code snippet in this article The Dangers of the Large Object Heap and implementing this code just after the catch block of the Fill function to fragment the LOH, as outlined by cfneese posted on 11/04/2011 in the comments for the bug Large Object Heap fragmentation causes OutOfmemoryException :

        unsafe
        {
            var w = new StreamWriter(@".\test.txt");
            for (int i = 0; i < count; i++)
            {
                var handle = GCHandle.Alloc(smallBlocks[i], GCHandleType.Pinned);
                w.WriteLine(String.Format("{0,10}\t{1,10}", i, handle.AddrOfPinnedObject()));
                handle.Free();
            }
            w.Close();
        }
like image 82
chridam Avatar answered Nov 09 '22 19:11

chridam