Could you describe how is memory management done in .NET?
Experience Level:
Senior
Tags:
.NET
ASP.NET MVC
ASP.NET WebAPI
ASP.NET WebForms
C#
Answer
General overview
The garbage collector allocates and frees virtual memory for you on the managed heap.
Key ideas
- CLR - Automatic memory management
- Managed memory
- Memory allocation
- Releasing memory
- Cleaning up unmanaged resources
- Garbage collector (GC)
- Managed heap
- Large Object Heap - 85000 bytes+
- Generations 0,1,2
- IDisposable/Dispose pattern
Secret weapons
- Value types are not always stored on stack.
- Allocation on a stack is only "the stack pointer" modification.
- Stack is just an implementation detail (think about other implementation of CLI=Common Language Infrastructure)
Memory concepts
- Each process has its own, separate virtual address space.
- By default, on 32-bit computers, each process has a 2-GB user-mode virtual address space.
Virtual memory
- Free/Reserved/Commited
- Virtual address space can get fragmented. This means that there are free blocks, also known as holes, in the address space.
- You can run out of memory if you run out of virtual address space to reserve or physical space to commit.
Excellent links
You must read these (no excuses):
- https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/
- https://blogs.msdn.microsoft.com/ericlippert/2009/05/04/the-stack-is-an-implementation-detail-part-two/
Related C# job interview questions
-
What is MSIL?
.NET ASP.NET MVC ASP.NET WebAPI ASP.NET WebForms C# Senior -
What is JIT?
.NET ASP.NET MVC ASP.NET WebAPI ASP.NET WebForms C# Senior -
Write a code that takes an integer number and outputs its digits to the console.
.NET C# Code challenge Mid-level -
What is variable capturing good for and how does it work?
.NET C# Senior -
What will be the output of the following code that is using delegates?
.NET C# Code challenge Senior