Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Memory Management

Introduction to Memory Management

Memory management in .NET refers to the automatic allocation and deallocation of memory for objects, managed by the Common Language Runtime (CLR).

Garbage Collection in .NET

.NET uses a garbage collector (GC) to automatically manage memory. It identifies and recycles objects that are no longer in use, freeing up memory for new allocations.

Example: Garbage Collection Basics


// In .NET, you don't explicitly free memory like in C++
// Garbage Collector automatically manages memory
// Example of object creation and usage
public class MyClass {
    public void DoSomething() {
        // Allocate memory for an object
        SomeClass obj = new SomeClass();
        
        // Use the object
        obj.DoWork();
        
        // Once 'obj' is no longer referenced, GC can reclaim its memory
    }
}
    

Memory Allocation

.NET allocates memory in two main segments: the stack and the heap. Value types are typically stored on the stack, while reference types are stored on the heap.

Example: Stack vs Heap


// Stack allocation (value types)
int num = 10;
double pi = 3.14;

// Heap allocation (reference types)
string message = "Hello, world!";
SomeClass obj = new SomeClass();
    

Finalizers and Dispose Pattern

Finalizers are used to release unmanaged resources held by objects. The Dispose pattern provides a way to release managed and unmanaged resources explicitly.

Example: Dispose Pattern


using System;

public class ResourceHolder : IDisposable {
    private IntPtr handle;
    private bool disposed = false;

    public ResourceHolder() {
        handle = IntPtr.Zero;
    }

    ~ResourceHolder() {
        Dispose(false);
    }

    public void Dispose() {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing) {
        if (!disposed) {
            if (disposing) {
                // Dispose managed resources
            }
            
            // Dispose unmanaged resources
            CloseHandle(handle);
            handle = IntPtr.Zero;
            
            disposed = true;
        }
    }

    private void CloseHandle(IntPtr handle) {
        // Close unmanaged resource
    }
}
    

Memory Performance Considerations

Proper memory management practices can improve performance and prevent issues like memory leaks or excessive garbage collection.

Conclusion

Memory management in .NET, handled by the CLR's garbage collector, automates the allocation and deallocation of memory, ensuring efficient use of resources and reducing the risk of memory-related errors.