Memory management in .NET: the journey of objects from creation to release
How the lifecycle of objects is managed in .NET: the Garbage Collector, the three generations, and how memory leaks are avoided.
Imagine a .NET program running along, like a universe of bustling objects – variables, lists, strings and other structures – all of them come into the world, carry out their tasks and… disappear. But what really happens there? How is the “birth” and “death” of objects managed? This is where the Garbage Collector (GC) comes into the picture.
Part 1: creating objects – the moment it all begins
Every time we create a new object, for example a list or a variable, we are requesting memory resources. If we assume this object is temporary, like a variable in a loop, the GC assigns it to the first generation, Generation 0, out of three generations of objects.
For example, look at the following function:
public int CalculateSum(List<int> numbers) {
int sum = 0;
foreach (var number in numbers) {
sum += number;
}
return sum;
}The variable sum is created and memory is allocated for it every time the function runs. It has a short lifetime, only for the duration of the loop. As soon as the function finishes running, it is no longer needed.
Part 2: the fate of objects – managed by the GC
When an object is no longer needed, like sum in the function above, it is effectively considered “garbage” in .NET. But the GC is in no hurry to free all the memory every time a small change occurs. It works in a smarter way, which lets the program run efficiently and in an organized manner.
In .NET, the GC uses a model of generations to manage objects:
- Generation 0: this is where short-lived objects are placed, such as local variables that are used only for a short time.
- Generation 1: objects that have survived a little longer are moved to this stage.
- Generation 2: this is the generation of long-lived objects, those that stay in memory for extended periods, such as the program’s configuration settings or objects that hold data throughout the program’s entire lifetime.
For example, when a program performs calculations at runtime, it might store all the results of all the calculations in some data structure, so that we can use them again and again:
public class Configuration {
public List<int> Settings { get; set; } = new List<int> { 5, 10, 15 };
}This list, Settings, is defined as long-lived because it is loaded when the program starts and is used again and again. It will therefore be found in Generation 2.
Part 3: preventing memory leaks – how does the GC make sure memory doesn’t run out?
A Memory Leak is a problem that can occur when objects we have finished using remain in memory without us being able to access them. If our program doesn’t know how to clean them up, they will take up all the memory, until at some point the program may crash. The GC prevents this situation by looking for objects that are no longer reachable (with no references) and freeing their memory.
The GC runs automatically when memory is full, or when it detects pressure. In other words, even if we have created a very large number of objects and memory is starting to fill up, the GC will run to free more space, so that the application can keep working.
A detailed example: how the GC works in practice
Suppose we have an application that works with a list of users temporarily, and finally displays information about active users only:
public List<User> GetActiveUsers(List<User> allUsers) {
List<User> activeUsers = new List<User>();
foreach (var user in allUsers) {
if (user.IsActive) {
activeUsers.Add(user);
}
}
return activeUsers;
}The variable activeUsers is a temporary variable created only while the function runs. Once the run is over, it is no longer needed. When activeUsers goes out of use, the GC knows it can free the memory it occupies and keep that memory available for future use.
Going further: how the GC divides its work by generation
Defining generations in the GC allows it to optimize when freeing memory:
- The first generation is checked very often, because it contains short-lived objects.
- The second generation is checked less frequently, because objects that got there are likely to survive longer.
- The third generation is checked very rarely, because it is intended for long-lived objects that stay in memory for as long as the program runs.
Summary
The GC is a smart system designed to manage the program’s memory automatically. It frees the memory of objects that are not in use, and prevents memory leaks by managing generations of objects according to their lifetime. This mechanism lets the program run efficiently, without having to constantly worry about freeing memory manually.
To finish, here is a reminder:
- Generation 0 is for temporary objects, such as local variables in functions.
- Generation 1 is for objects that live a little longer, but will still be freed soon.
- Generation 2 is for long-lived objects that survive throughout the program’s entire lifetime.
Memory management by the GC is one of the main advantages of .NET, and it gives programmers a working environment that lets them focus on development without worrying about the memory layout at every given moment.