Custom-Authorization-Policies :👈 👉:Health-Checks-Readiness-and-Liveness-Probes

ASP.NET Core Memory Management: Garbage Collection, Allocation and Performance

ASP.NET Core Memory Management: Garbage Collection, Allocation and Performance

1. Introduction to Memory Management

Memory management is the process of allocating, using, and releasing memory while an application is running.

In ASP.NET Core, memory management is primarily handled by the .NET runtime. Developers do not normally allocate and release managed memory manually.

However, developers must understand how memory allocation, garbage collection, object lifetimes, caching, and resource disposal work to build high-performance applications.

Why is memory management important?

  • Improves application performance.
  • Reduces unnecessary memory consumption.
  • Prevents memory leaks.
  • Reduces garbage collection overhead.
  • Improves application scalability.
  • Helps applications handle more concurrent requests.

2. How .NET Memory Management Works

When an ASP.NET Core application creates objects, the .NET runtime allocates memory for those objects.

The Garbage Collector (GC) automatically identifies objects that are no longer reachable and reclaims their memory.

Basic memory management flow

ASP.NET Core Application Object Allocation Managed Heap Garbage Collector (GC) Objects are stored here Reclaims eligible memory

3. Managed Memory vs Unmanaged Memory

3.1 Managed Memory

Managed memory is memory allocated and controlled by the .NET runtime.

The Garbage Collector automatically manages the lifetime of managed objects.

Examples:

public void Process()
{
    string name = "John";
    int[] numbers = new int[1000];
    var customer = new Customer();
}

Here, the string, array, and Customer object are managed objects.

3.2 Unmanaged Memory

Unmanaged memory is memory or resources that are not automatically managed by the .NET Garbage Collector.

Examples include:

  • Native memory allocated through operating system APIs.
  • Memory allocated using native libraries.
  • Some resources used by database and network libraries.
  • Operating system handles and file handles.

Unmanaged resources often require explicit cleanup through Dispose() or another appropriate release mechanism.

Difference between managed and unmanaged memory

Managed Memory Unmanaged Memory
Controlled by .NET runtime. Controlled by native code or operating system APIs.
Garbage Collector reclaims eligible objects. Usually requires explicit resource cleanup.
Examples: strings, arrays, objects. Examples: native allocations and operating system handles.
Memory reclamation is automatic. Cleanup depends on the resource API.

4. Understanding the .NET Garbage Collector (GC)

The Garbage Collector is a component of the .NET runtime responsible for automatically managing managed memory.

It identifies objects that are no longer reachable from application roots and reclaims their memory.

How Garbage Collection works

  1. The application creates objects.
  2. The objects are allocated on the managed heap.
  3. The application uses references to access the objects.
  4. Some objects eventually become unreachable.
  5. The GC identifies unreachable objects.
  6. The GC reclaims their memory and may compact the heap.

Garbage Collection diagram

Before GC Object A Object B Object C Object D GC After GC Object A Object C Unreachable objects reclaimed Memory becomes available for future allocations

Important: The GC does not simply delete every object that is not currently being used in a method. It determines reachability by examining references from GC roots.

5. What Are GC Roots?

GC roots are references from which the Garbage Collector determines whether an object is reachable.

Common GC roots include:

  • Local variables that are currently live on thread stacks.
  • Static fields.
  • CPU registers and runtime-maintained references.
  • GC handles.

If an object can be reached through a chain of references starting from a GC root, it is considered reachable and cannot be collected.

public class CustomerService
{
    private static Customer _customer = new Customer();
    public void Process()
    {
        Console.WriteLine(_customer.Name);
    }
}

The static field keeps the Customer object reachable while the static reference remains available.

6. Generational Garbage Collection

.NET uses generational garbage collection to improve efficiency.

The managed heap is divided into three generations:

  • Generation 0: Contains newly allocated, short-lived objects.
  • Generation 1: Contains objects that survived a Generation 0 collection.
  • Generation 2: Contains longer-lived objects that survived earlier collections.

Generational GC diagram

Generation 0 Newly allocated, short-lived objects Generation 1 Objects that survived Gen 0 collection Generation 2 Long-lived objects

How objects move between generations

  1. A newly created object is normally allocated in Generation 0.
  2. If it survives a Generation 0 collection, it may be promoted to Generation 1.
  3. If it survives a Generation 1 collection, it may be promoted to Generation 2.
  4. Generation 2 collections generally involve more heap memory and can be more expensive.

Example: A temporary object created while processing an API request may be collected quickly. An application-wide configuration object may remain alive for the entire application lifetime.

7. Large Object Heap (LOH)

The Large Object Heap stores large managed objects. Objects approximately 85,000 bytes or larger are generally allocated on the LOH.

Examples include:

  • Large byte arrays.
  • Large character arrays.
  • Large arrays of reference types.
byte[] smallBuffer = new byte[1024];
// A large allocation, generally placed on the LOH
byte[] largeBuffer = new byte[100000];

The LOH is generally collected as part of Generation 2 garbage collection.

Why should we care about LOH?

  • Frequent large allocations can increase GC pressure.
  • Large objects can increase memory usage significantly.
  • LOH fragmentation can affect memory efficiency.

Optimization: Reuse large buffers when appropriate instead of repeatedly allocating new ones.

8. What Is Stack Memory and Heap Memory?

Stack memory

The stack stores method execution information, including local value-type variables in many cases, references, and return information.

Each thread has its own stack.

Heap memory

The managed heap stores objects whose memory is managed by the .NET Garbage Collector.

Objects created using new are generally allocated on the managed heap, including objects that contain value-type fields.

public void Calculate()
{
    int age = 25;
    Customer customer = new Customer();
}

Here:

  • age is a value-type local variable and may be stored in a register or stack location depending on JIT optimization.
  • customer is a reference to a Customer object.
  • The Customer object is normally allocated on the managed heap.

Do not assume that every value type is stored on the stack. Value types can also be fields inside heap objects, elements inside arrays, or boxed objects.

9. Value Types vs Reference Types

Value Types Reference Types
Contain their value directly. Contain a reference to an object.
Examples: int, bool, double, struct. Examples: class, string, array, delegate.
Assignment generally copies the value. Assignment generally copies the reference.
Can be stored inline inside other objects. Objects are generally allocated on the managed heap.
int first = 10;
int second = first;
second = 20;
Console.WriteLine(first);  // 10
Console.WriteLine(second); // 20
Customer first = new Customer();
first.Name = "John";
Customer second = first;
second.Name = "David";
Console.WriteLine(first.Name); // David

In the second example, both variables refer to the same Customer object.

10. Memory Allocation in ASP.NET Core

Memory allocations happen frequently while processing HTTP requests.

For example, an API may allocate:

  • Request and response objects.
  • DTOs and entity objects.
  • Strings and temporary collections.
  • LINQ query results.
  • Serialization buffers.
  • Logging state and exception objects.

Example of an API allocation

[HttpGet]
public IActionResult GetCustomers()
{
    var customers = new List<Customer>();
    for (int i = 1; i <= 1000; i++)
    {
        customers.Add(new Customer
        {
            Id = i,
            Name = "Customer " + i
        });
    }
    return Ok(customers);
}

This method creates a list, 1,000 Customer objects, and strings. It also involves response serialization allocations.

If this endpoint receives many requests, these allocations can create significant GC pressure.

11. What Is Allocation Pressure?

Allocation pressure occurs when an application creates objects frequently, causing the runtime to perform more garbage collection work.

For example, imagine an API receives 1,000 requests per second and creates many temporary objects for every request.

Even if those objects are short-lived, the GC must periodically reclaim their memory.

How to reduce allocation pressure

  • Avoid unnecessary object creation.
  • Reuse expensive objects where safe.
  • Avoid unnecessary string concatenation.
  • Use appropriate collection sizes.
  • Use streaming for large responses.
  • Use pooling for suitable high-volume buffers.
  • Avoid materializing large datasets unnecessarily.

12. String Allocation and Optimization

Strings in .NET are immutable. This means that once a string is created, its contents cannot be changed.

Repeated concatenation can create many temporary strings.

Less efficient example

string result = "";
for (int i = 0; i < 1000; i++)
{
    result += i.ToString();
}

Each concatenation can create a new string object.

Better approach using StringBuilder

var builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    builder.Append(i);
}
string result = builder.ToString();

StringBuilder reduces intermediate string allocations in repeated concatenation scenarios.

For a small, fixed number of concatenations, normal string interpolation or concatenation is often perfectly fine.

13. Boxing and Unboxing

Boxing converts a value type into an object reference. This normally creates a boxed object on the managed heap.

Unboxing extracts the value from a boxed object.

Boxing example

int number = 100;
object value = number; // Boxing
int result = (int)value; // Unboxing

Boxing can create additional allocations, especially when repeated frequently.

Avoid unnecessary boxing

Prefer generic collections instead of non-generic collections when storing value types.

// May involve boxing
ArrayList values = new ArrayList();
values.Add(10);
// Avoids boxing for the stored int value
List<int> numbers = new List<int>();
numbers.Add(10);

14. LINQ and Memory Allocations

LINQ makes code readable, but some LINQ operations may create iterators, delegates, intermediate collections, or result objects.

Example

var activeCustomers = customers
    .Where(x => x.IsActive)
    .Select(x => new CustomerDto
    {
        Id = x.Id,
        Name = x.Name
    })
    .ToList();

This creates a new DTO for each selected customer and a result list.

For most application code, this is acceptable. Optimize only when profiling shows that the allocations matter.

Use database filtering

For Entity Framework Core, filter data in the database instead of loading every record into memory first.

var activeCustomers = await dbContext.Customers
    .Where(x => x.IsActive)
    .Select(x => new CustomerDto
    {
        Id = x.Id,
        Name = x.Name
    })
    .ToListAsync();

This allows the database to filter and project the required columns before returning the results.

15. IDisposable and Resource Management

The Garbage Collector manages managed memory, but it does not immediately release operating system resources such as file handles, database connections, and network resources.

The IDisposable interface provides a standard way to release resources deterministically.

Example using IDisposable

using var file = new FileStream(
    "data.txt",
    FileMode.Open,
    FileAccess.Read);
using var reader = new StreamReader(file);
string content = reader.ReadToEnd();

The compiler ensures that the disposable resources are disposed when execution leaves the scope, including when an exception occurs.

Why use using?

  • Ensures resources are released promptly.
  • Works when exceptions occur.
  • Reduces resource leaks.
  • Makes cleanup easier to maintain.

ASP.NET Core dependency injection and disposal

When a disposable service is created and owned by the built-in dependency injection container, the container disposes it when its lifetime ends.

builder.Services.AddScoped<MyService>();

A scoped service is normally disposed at the end of its request scope.

Do not manually dispose a service resolved from dependency injection unless you explicitly own its lifetime.

16. Memory Leaks in ASP.NET Core

A memory leak occurs when memory or resources remain retained even though the application no longer needs them.

In managed .NET applications, a common cause is keeping unnecessary objects reachable through references.

Common causes

  • Static collections that continuously grow.
  • Event handlers that are never unsubscribed.
  • Long-lived objects holding references to short-lived objects.
  • Unbounded application caches.
  • Unreleased unmanaged resources.
  • Background tasks retaining large object graphs.

Example of a memory leak

public class CacheService
{
    private static readonly List<Customer> Customers = new();
    public void Add(Customer customer)
    {
        Customers.Add(customer);
    }
}

This static collection remains reachable for the lifetime of the application. If customers are continually added and never removed, memory consumption can keep growing.

Better approach

Use a bounded cache with expiration or an explicit retention policy when storing temporary data.

public class CustomerCache
{
    private readonly IMemoryCache _cache;
    public CustomerCache(IMemoryCache cache)
    {
        _cache = cache;
    }
    public void Set(Customer customer)
    {
        _cache.Set(
            $"customer-{customer.Id}",
            customer,
            TimeSpan.FromMinutes(10));
    }
}

Expiration helps control retention time. For production caches, also consider size limits and an appropriate eviction policy.

17. IMemoryCache in ASP.NET Core

IMemoryCache stores data in the application's memory.

It can reduce repeated database calls and improve response times.

Register memory cache

builder.Services.AddMemoryCache();

Use memory cache

public class ProductService
{
    private readonly IMemoryCache _cache;
    public ProductService(IMemoryCache cache)
    {
        _cache = cache;
    }
    public async Task<Product?> GetProductAsync(
        int id)
    {
        return await _cache.GetOrCreateAsync(
            $"product-{id}",
            async entry =>
            {
                entry.AbsoluteExpirationRelativeToNow =
                    TimeSpan.FromMinutes(5);
                return await LoadProductFromDatabase(id);
            });
    }
    private Task<Product?> LoadProductFromDatabase(int id)
    {
        // Database lookup goes here.
        throw new NotImplementedException();
    }
}

Important cache considerations

  • Set appropriate expiration policies.
  • Set size limits where suitable.
  • Remove outdated entries.
  • Avoid caching large objects without a retention policy.
  • Remember that each application instance has its own in-memory cache.

For multiple application instances that need shared cached data, consider a distributed cache such as Redis.

18. ArrayPool<T> - Reusing Arrays

ArrayPool<T> allows applications to reuse arrays instead of allocating new arrays repeatedly.

It is useful in high-throughput scenarios involving temporary buffers.

Example

using System.Buffers;
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
    // Use the buffer.
    // The rented array may be larger than 4096.
}
finally
{
    ArrayPool<byte>.Shared.Return(
        buffer,
        clearArray: true);
}

Important: Always return the array to the pool when finished. Do not use it after returning it.

If the array contains sensitive information, clear it before reuse. Be aware that clearing has a performance cost.

19. MemoryPool<T>

MemoryPool<T> provides reusable memory blocks through disposable memory owners.

It can be useful when working with APIs that consume Memory<T>.

using System.Buffers;
using IMemoryOwner<byte> owner =
    MemoryPool<byte>.Shared.Rent(4096);
Memory<byte> memory = owner.Memory;
memory.Span[0] = 100;
// Memory is returned when owner is disposed.

Use the memory only while its owner remains alive. Do not retain the memory after disposing the owner.

20. Span<T> and Memory<T>

Span<T> and Memory<T> help process contiguous memory efficiently without necessarily creating additional arrays or copies.

Span<T>

Span<T> is a stack-only type that provides a view over contiguous memory.

byte[] data = { 10, 20, 30, 40, 50 };
Span<byte> span = data.AsSpan();
span[0] = 99;
Console.WriteLine(data[0]); // 99

Memory<T>

Memory<T> provides a memory view that can be stored and used across asynchronous operations.

byte[] data = new byte[100];
Memory<byte> memory = data.AsMemory();
await ProcessAsync(memory);
static async Task ProcessAsync(Memory<byte> memory)
{
    await Task.Delay(10);
    memory.Span[0] = 50;
}

Span vs Memory

Span<T> Memory<T>
Stack-only ref struct. Can be stored in ordinary objects.
Cannot be used as a local across an await boundary. Can be used across asynchronous operations.
Provides direct memory access. Provides a memory view.
Useful for synchronous processing. Useful for asynchronous processing.

21. Object Pooling

Object pooling means reusing existing objects instead of creating new objects repeatedly.

ASP.NET Core provides object pooling support through the Microsoft.Extensions.ObjectPool package.

Example using ObjectPool

using Microsoft.Extensions.ObjectPool;
public class StringBuilderPooledPolicy
    : PooledObjectPolicy<StringBuilder>
{
    public override StringBuilder Create()
    {
        return new StringBuilder();
    }
    public override StringBuilder Return(
        StringBuilder obj)
    {
        obj.Clear();
        return obj;
    }
}

Register the pool:

builder.Services.AddSingleton<ObjectPoolProvider,
    DefaultObjectPoolProvider>();
builder.Services.AddSingleton<ObjectPool<StringBuilder>>(sp =>
{
    var provider = sp.GetRequiredService<ObjectPoolProvider>();
    return provider.Create(new StringBuilderPooledPolicy());
});

Use the pool:

public class ReportService
{
    private readonly ObjectPool<StringBuilder> _pool;
    public ReportService(ObjectPool<StringBuilder> pool)
    {
        _pool = pool;
    }
    public string Generate()
    {
        var builder = _pool.Get();
        try
        {
            builder.Append("Monthly Report");
            return builder.ToString();
        }
        finally
        {
            _pool.Return(builder);
        }
    }
}

Pooling is not automatically faster. Use it when profiling demonstrates that repeated object creation is a meaningful cost.

22. Server GC vs Workstation GC

.NET supports different garbage collection modes.

Workstation GC

  • Designed primarily for client applications.
  • Balances application responsiveness and memory management.
  • Typically uses fewer GC resources.

Server GC

  • Designed for server workloads.
  • Uses multiple GC heaps and dedicated GC threads where supported.
  • Can improve throughput on multi-core systems.
  • May consume more memory and processing resources.

ASP.NET Core applications commonly use Server GC by default when hosted in typical server configurations, but the actual mode depends on runtime configuration and hosting environment.

Configuration example

In the project file, you can explicitly configure Server GC:

<PropertyGroup>
    <ServerGarbageCollection>true</ServerGarbageCollection>
</PropertyGroup>

Do not change GC mode without measuring the application's actual workload.

23. GC Modes: Background and Blocking Collection

The .NET GC supports different collection behaviors.

Background GC

Background garbage collection allows a Generation 2 collection to run concurrently with managed application threads in supported scenarios.

This helps reduce pauses during server workloads.

Blocking GC

Blocking collection pauses managed application threads while the collection performs required work.

Short pauses are normal, but frequent or long pauses can affect application latency.

24. GC.Collect() - Should We Call It Manually?

GC.Collect() requests that the Garbage Collector perform a collection.

GC.Collect();

In normal ASP.NET Core application code, avoid calling it manually.

Why avoid it?

  • The runtime already determines when collection is appropriate.
  • Manual collection can introduce unnecessary pauses.
  • It may increase CPU usage.
  • It can negatively affect application throughput.

Use manual collection only in carefully measured, specialized scenarios where its behavior is clearly justified.

25. Async and Memory Management

Asynchronous programming helps ASP.NET Core handle concurrent I/O operations efficiently. However, async methods can still allocate objects.

Example

public async Task<Product?> GetProductAsync(int id)
{
    return await _dbContext.Products
        .FirstOrDefaultAsync(x => x.Id == id);
}

Async methods may involve state machines and task objects. The compiler and runtime optimize many common cases, so avoid assuming every async method creates a separate heap allocation.

Use async correctly

  • Use async database operations.
  • Use async network and file I/O operations.
  • Avoid blocking asynchronous work with .Result or .Wait().
  • Avoid creating unnecessary tasks.
  • Do not use async for purely CPU-bound work without a specific reason.

26. Common Memory Management Mistakes

Mistake Problem Better Approach
Unbounded static collections Objects remain reachable. Use bounded storage and eviction.
Repeated string concatenation Creates intermediate strings. Use StringBuilder for repeated concatenation.
Unnecessary large allocations Increases LOH and GC pressure. Reuse buffers or stream data.
Not disposing resources Resource handles remain occupied. Use using or await using.
Unnecessary ToList() Materializes additional collections. Use deferred execution where appropriate.
Manual GC.Collect() Can cause unnecessary pauses. Allow the runtime to manage GC.
Unbounded memory cache Cache may grow continuously. Use size limits and expiration.
Loading entire database tables Consumes unnecessary memory. Use filtering, projection and pagination.

27. How to Monitor Memory Usage

Memory monitoring helps identify memory growth, allocation pressure, and GC problems.

Useful tools

  • dotnet-counters: Monitors runtime counters such as GC heap size and allocation rate.
  • dotnet-gcdump: Captures a GC heap dump for analysis.
  • dotnet-dump: Collects and analyzes process dumps.
  • Visual Studio Diagnostic Tools: Helps investigate memory usage and allocations.
  • PerfView: Provides detailed performance and GC analysis.
  • Application Insights: Helps monitor application performance and telemetry.

Monitor using dotnet-counters

dotnet-counters monitor -p <process-id> System.Runtime

Useful runtime metrics include:

  • GC Heap Size.
  • Allocation Rate.
  • Gen 0 GC Count.
  • Gen 1 GC Count.
  • Gen 2 GC Count.
  • Time in GC.
  • LOH Size.
  • Working Set.

28. Memory Optimization in ASP.NET Core APIs

1. Use pagination

var products = await dbContext.Products
    .OrderBy(x => x.Id)
    .Skip(0)
    .Take(50)
    .ToListAsync();

Pagination avoids loading an unnecessarily large result set into memory. For large datasets, keyset pagination may perform better than large Skip values.

2. Use AsNoTracking for read-only queries

var products = await dbContext.Products
    .AsNoTracking()
    .Where(x => x.IsActive)
    .ToListAsync();

AsNoTracking avoids the normal change-tracking overhead for read-only entity queries.

3. Select only required columns

var products = await dbContext.Products
    .Select(x => new ProductDto
    {
        Id = x.Id,
        Name = x.Name
    })
    .ToListAsync();

This reduces unnecessary data transfer and object materialization.

4. Stream large responses

For large datasets, streaming can avoid creating a complete in-memory collection before writing the response.

[HttpGet("export")]
public async Task Export(CancellationToken cancellationToken)
{
    Response.ContentType = "text/plain";
    await foreach (var product in _dbContext.Products
        .AsNoTracking()
        .AsAsyncEnumerable()
        .WithCancellation(cancellationToken))
    {
        await Response.WriteAsync(
            $"{product.Id},{product.Name}\n",
            cancellationToken);
    }
}

Streaming must be designed carefully: database readers and request resources remain occupied while the response is being written.

5. Avoid unnecessary response data

Return only the fields that the client actually needs.

29. Real-World ASP.NET Core Memory Optimization Example

Before optimization

[HttpGet]
public async Task<IActionResult> GetProducts()
{
    var products = await _dbContext.Products
        .ToListAsync();
    var result = products
        .Where(x => x.IsActive)
        .Select(x => new ProductDto
        {
            Id = x.Id,
            Name = x.Name
        })
        .ToList();
    return Ok(result);
}

Problems:

  • Loads all products into application memory.
  • Tracks entities even though they are only read.
  • Filters after retrieving data.
  • Creates an additional result collection.

After optimization

[HttpGet]
public async Task<IActionResult> GetProducts(
    int page = 1,
    int pageSize = 50)
{
    page = Math.Max(1, page);
    pageSize = Math.Clamp(pageSize, 1, 100);
    var products = await _dbContext.Products
        .AsNoTracking()
        .Where(x => x.IsActive)
        .OrderBy(x => x.Id)
        .Skip((page - 1) * pageSize)
        .Take(pageSize)
        .Select(x => new ProductDto
        {
            Id = x.Id,
            Name = x.Name
        })
        .ToListAsync();
    return Ok(products);
}

Benefits:

  • Database filters the records.
  • Only required columns are selected.
  • Change tracking is avoided.
  • Only a limited number of records are materialized.
  • Application memory usage is reduced for large datasets.

30. Production Best Practices

  1. Monitor GC heap size and allocation rate.
  2. Investigate continuous memory growth.
  3. Use profiling before optimizing allocations.
  4. Dispose resources deterministically.
  5. Use bounded caches with expiration and eviction.
  6. Avoid unnecessary object creation in high-throughput paths.
  7. Use streaming for suitable large-data scenarios.
  8. Use ArrayPool for suitable repeated buffer allocations.
  9. Use AsNoTracking for read-only EF Core entity queries.
  10. Use pagination for large database results.
  11. Avoid manual garbage collection in ordinary application code.
  12. Test memory behavior under realistic concurrent workloads.

31. Interview Questions and Answers

Q1. What is Garbage Collection in .NET?

Garbage Collection is an automatic memory management mechanism that identifies unreachable managed objects and reclaims their memory.

Q2. What are GC generations?

Generation 0 contains newer objects, Generation 1 contains objects that survived Gen 0 collection, and Generation 2 contains longer-lived objects.

Q3. What is LOH?

The Large Object Heap stores large objects, generally those approximately 85,000 bytes or larger. It is collected as part of Gen 2 collection.

Q4. What is boxing?

Boxing converts a value type into an object reference and normally allocates a boxed object on the managed heap.

Q5. What is a memory leak in .NET?

A memory leak occurs when unnecessary objects remain reachable and therefore cannot be collected.

Q6. What is IDisposable?

IDisposable provides a standard mechanism for deterministic cleanup of resources such as file handles and other disposable resources.

Q7. What is ArrayPool?

ArrayPool allows applications to rent and return reusable arrays to reduce repeated array allocations.

Q8. What is the difference between Span and Memory?

Span is a stack-only memory view, while Memory can be stored and used across asynchronous operations.

Q9. What is Server GC?

Server GC is a garbage collection mode designed for server workloads and can improve throughput on multi-core systems.

Q10. Why should we avoid GC.Collect()?

Manual collection can introduce unnecessary pauses and CPU overhead. The runtime generally makes better collection decisions using its allocation and heap information.

Q11. How do you investigate a memory leak?

Monitor memory and GC metrics, collect heap dumps, compare retained object graphs, and identify references that keep unnecessary objects alive.

Q12. How do you reduce memory consumption in an ASP.NET Core API?

Use pagination, database-side filtering, projection, AsNoTracking, bounded caching, streaming where appropriate, and avoid unnecessary allocations.

32. Quick Revision

Concept Meaning
GC Automatically reclaims unreachable managed objects.
Managed Heap Memory used for managed objects.
Gen 0 Newer, usually short-lived objects.
Gen 1 Objects surviving Gen 0 collection.
Gen 2 Long-lived objects.
LOH Heap for large objects.
IDisposable Deterministic resource cleanup.
IMemoryCache In-process memory caching.
ArrayPool Reusable array buffers.
Span Stack-only view over contiguous memory.
Memory Memory view usable across async operations.
Object Pooling Reuse objects instead of repeatedly creating them.

33. Official Microsoft Documentation

🔙
Custom-Authorization-Policies :👈 👉:Health-Checks-Readiness-and-Liveness-Probes