DEV Community

Cover image for C# - Optimize Performance with Span<T> and Memory<T>
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Optimize Performance with Span<T> and Memory<T>

C# introduced Span<T> and Memory<T> as part of its more recent versions, offering more efficient ways to handle slices of arrays, strings, and other types of memory. These types are particularly useful for high-performance scenarios because they provide a way to work with portions of data without creating additional allocations.

Here's how you can use Span<T> and Memory<T>:

  1. Use Span<T> for Stack-only Scenarios:
    Span<T> is a stack-only type that can point to a contiguous region of memory, such as an array segment. It's ideal for temporary slices of data in methods or short-lived operations.

  2. Use Memory<T> for Heap Scenarios:
    Memory<T> is similar to Span<T> but can be stored in heap-allocated memory, making it suitable for use in async methods or when you need to pass the data around.

Example:

public static void ProcessArray()
{
    int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    // Using Span<T> for a slice of the array
    Span<int> slice = numbers.AsSpan(2, 5); // Slice with elements 2, 3, 4, 5, 6

    // Modify the slice
    for (int i = 0; i < slice.Length; i++)
    {
        slice[i] *= 2;
    }

    // Using Memory<T> for asynchronous operations
    Memory<int> memory = numbers.AsMemory(2, 5);

    ProcessMemoryAsync(memory);
}

public static async Task ProcessMemoryAsync(Memory<int> data)
{
    // Do something with the data asynchronously
    await Task.Delay(100); // Simulate async work
    foreach (var item in data.Span.ToArray())
    {
        Console.WriteLine(item);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, Span<T> is used for a synchronous modification of an array segment, while Memory<T> is used for asynchronous processing. These types are particularly useful in scenarios involving array manipulations, buffer management, or when working with large datasets.

By using Span<T> and Memory<T>, you can significantly reduce memory allocations and improve the performance of your applications, particularly in scenarios with high computational demands or large data processing requirements.

Top comments (0)