Introduction

When I started diving into performance in C#, I realised there’s a hidden layer behind every line of code, particularly in terms of memory usage. The way we store, access, and pass data around can mean the difference between a smooth app and a laggy mess.

So, let’s go on a recap starting from the basics and building up to some of the coolest features in modern C#, like Span<T>.

The Foundation — Stack and Heap

Before we can talk about Span<T> or even “contiguous memory,” we need to know where our data lives.

Stack

Heap

Think of the stack as a desk in front of you — quick access but limited space. The heap is a big warehouse, but you need a forklift (GC) to manage it.

struct — The Lightweight Data Container

Now that we know about the stack, let’s meet its close friend: struct.

A struct is,

public struct Point(int x, int y)
{
    public int X = x, Y = y;
}

Point p1 = new(3, 4);
Point p2 = p1; // Copy — p2 is independent
p2.X = 10;
Console.WriteLine($"p1: ({p1.X}, {p1.Y})");
Console.WriteLine($"p2: ({p2.X}, {p2.Y})");
///////////////////////////////////////////////////////
Output:
p1: (3, 4)
p2: (10, 4)

This clearly shows that p1 stays unchanged after modifying p2, proving that structs are copied by value.

Contiguous Memory — The Secret to Speed

Some data structures store items in contiguous memory, meaning all elements sit right next to each other in one block.

[ 10 ][ 20 ][ 30 ][ 40 ]

Why is this good?

Why List<T> Is Contiguous… But Not Quite?

At first glance, List<T> seems contiguous; it wraps an internal array.

But there’s a catch.

So, List<T> can’t directly be treated as a block of memory the way arrays or Span<T> can.

Span<T> — Memory Manipulation Without the Cost

Span<T> lets you work with slices of contiguous memory without creating new arrays or copying data.

Traditionally, in C#,

Span<T> changes this.

Why Span<T> Is a ref struct?

Unlike normal structs, Span<T> is a ref struct, which means.

Why?

Because Span<T> points directly into memory, letting it move to the heap would risk dangling pointers and unsafe memory access.

Final Takeaways

By understanding,

Thank You, and Stay Tuned for More!

More Articles from my Account.