Day 23 of 30-Day .NET Challenge: Span<T> over Arrays

Day 23 of 30-Day .NET Challenge: Span<T> over Arrays

Optimization involves choosing Span<T> over Arrays for manipulating memory regions. Discover a better approach using Spans on Day 23 of our 30-Day .NE


The article demonstrates the use of Span<T> for optimizing memory management, highlighting the performance benefits.

Learning Objectives

  • Drawbacks of the array in memory management

  • Efficiency of Spans

Prerequisites for Developers

  • Basic understanding of C# programming language.

30 Day .Net Challenge
Edit description

Getting Started

The drawbacks of Arrays

Generally, developers use an array to store sequences of elements in continuous memory locations. Arrays are quite simple and easy to understand. A code snippet of the byte array is shown below

// Bad way: Using arrays may lead to unnecessary memory allocations and copying
byte[] data = GetData();

The problem with the above code is that it may lead to unnecessary memory allocations and copying because GetData creates a new array each time. The aforementioned code block will degrade the performance of the applications that require high data processing or applications that have limited memory resources.

Efficiency of Spans

Please find below the refactored version of the previous code snippet.

// Good way: Using Span<T> avoids additional memory allocation and copying
byte[] data = GetData();
Span<byte> dataSpan = data.AsSpan();

The Span<T> provides a type-safe and memory-safe view of contiguous memory regions without worrying about the copy issue highlighted previously.

Using the AsSpan() method creates a view of the original array without copying or creating a new memory each time.

Complete Code

Create another class named SpanOverArrayand add the following code snippet

public static class SpanOverArray
    public static void ProcessData(byte[] data)
        Console.WriteLine("Processing byte array:");
        foreach (var b in data)
            Console.Write($"{b} ");

    public static void ProcessData(Span<byte> dataSpan)
        Console.WriteLine("Processing Span<byte>:");
        foreach (var b in dataSpan)
            Console.Write($"{b} ");

Execute from the main method as follows

#region Day 23: Span Over Arrays
static string ExecuteDay23()

    byte[] largeData = new byte[100]; // Simulate a large data set
    Random rng = new Random();
    rng.NextBytes(largeData); // Populate with random bytes

    // Process using array slice
    byte[] slice = new byte[10]; // Creating a new array for the slice
    Array.Copy(largeData, 10, slice, 0, 10); // Copying data

    // Process using Span<T>
    Span<byte> span = largeData.AsSpan(10, 10); // Creating a span starting at index 10
    return "Executed Day 23 successfully..!!";


Console Output

Processing byte array:
75 20 132 37 218 170 182 227 224 146

Processing Span<byte>:
75 20 132 37 218 170 182 227 224 146

Complete Code on GitHub

GitHub — ssukhpinder/30DayChallenge.Net

C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: Youtube | X | LinkedIn |
Visit our other platforms: GitHub
More content at C# Programming

Did you find this article valuable?

Support Sukhpinder Singh by becoming a sponsor. Any amount is appreciated!