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

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

Introduction

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

Learning Objectives

Prerequisites for Developers

30 Day .Net Challenge

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(); ProcessData(data);
Enter fullscreen mode
Exit fullscreen mode

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(); ProcessData(dataSpan);
Enter fullscreen mode
Exit fullscreen mode

The Span 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} "); } Console.WriteLine("\n"); } public static void ProcessData(Span<byte> dataSpan) { Console.WriteLine("Processing Span<byte>:"); foreach (var b in dataSpan) { Console.Write($"{b} "); } Console.WriteLine("\n"); } }
Enter fullscreen mode
Exit fullscreen mode

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 SpanOverArray.ProcessData(slice); // Process using Span<T> Span<byte> span = largeData.AsSpan(10, 10); // Creating a span starting at index 10 SpanOverArray.ProcessData(span); return "Executed Day 23 successfully..!!"; } #endregion
Enter fullscreen mode
Exit fullscreen mode

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
Enter fullscreen mode
Exit fullscreen mode

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 | Dev.to
Visit our other platforms: GitHub
More content at C# Programming


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Point loma seafoods near me | near me direct | directory.