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):

 

 

Related C# job interview questions
.NET challenge
.NET challenge

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself