Day 28 of 30-Day .NET Challenge: Use Stackalloc
Tags: dotnet, csharp, beginners, programming
Published: 2024-04-18 05:47:00

Learn to enhance your performance with stackalloc in C#. Discover a better approach on Day 28 of our 30-Day .NET Challenge.

## Introduction

.Net applications rely on a Garbage collector for memory allocation and deallocation, which simplifies memory management but leads to performance degradation if not managed efficiently. The article demonstrates how to use stackalloc to enhance application performance.

### Learning Objectives

* Understanding what is stackalloc

* Problem with traditional heap allocation

* Optimal use of stackalloc

### Prerequisites for Developers

* Basic understanding of C# programming language.

* Familiar with for loops

[30 Day .Net Challenge](https://singhsukhpinder.medium.com/list/52a751260fe1)

## Getting Started

### Understanding what is stackalloc

Stackalloc is a reserved keyword in C# which helps to allocate memory on the stack instead of heap which is managed by Garbage Collector whereas stack allocation is automatically freed once method execution ends.

### Problem with traditional heap allocation

Consider the following code example wherein the memory for the double array is allocation on the heap.
```csharp
    private double CalculateSum(double[] values)
    {
        double sum = 0;
        for (int i = 0; i < values.Length; i++)
        {
            sum += values[i];
        }
        return sum;
    }
```
If the aforementioned method is called frequently, then it creates an overhead for garbage collection which slows down the application performance.

### Optimal use of stackalloc

Please find below the refactored version of the previous code snippet
```csharp
    private unsafe double CalculateSum(int count)
    {
        double sum = 0;
        double* values = stackalloc double[count];  // Allocate memory on the stack
        for (int i = 0; i < count; i++)
        {
            values[i] = SomeValue(i);  // Assume SomeValue is a method returning a double
            sum += values[i];
        }
        return sum;
    }
```
In the above method, the values are allocated on stack rather than heap. In this approach there is no need for garbage collection, leading to faster execution and can reduce the pressure on GC.

For performance-sensitive applications, memory management is critical hence using stackalloc a developer can perform memory allocation/deallocation efficiently.

## Complete Code

Create another class named StackAlloc and add the following code snippet
```csharp
    public static class StackAlloc
    {
        static int count = 10000;  // Number of elements
        static double[] values = new double[count];
        public static void BadWay() {
    
            FillValues(values);
            // Calculate sum using heap allocation
    
            double heapSum = CalculateSumHeap(values);
            Console.WriteLine($"Heap allocation sum: {heapSum}");
    
        }
        public static void GoodWay()
        {
    
            FillValues(values);
    
            // Calculate sum using stackalloc
            double stackSum = CalculateSumStackalloc(count);
            Console.WriteLine($"Stackalloc sum: {stackSum}");
        }
        private static void FillValues(double[] values)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = SomeValue(i);
            }
        }
    
        private static double SomeValue(int i)
        {
            // Just a sample value function
            return i * 2.5;
        }
    
        private static double CalculateSumHeap(double[] values)
        {
            double sum = 0;
            for (int i = 0; i < values.Length; i++)
            {
                sum += values[i];
            }
            return sum;
        }
    
        private static unsafe double CalculateSumStackalloc(int count)
        {
            double sum = 0;
            double* values = stackalloc double[count];
            for (int i = 0; i < count; i++)
            {
                values[i] = SomeValue(i);
                sum += values[i];
            }
            return sum;
        }
    }
```
## Execute from the main method as follows
```csharp
    #region Day 28: Use Stackalloc
    static string ExecuteDay28()
    {
        StackAlloc.BadWay();
        StackAlloc.GoodWay();
        
        return "Executed Day 28 successfully..!!";
    }
    
    #endregion
```
## Console Output
```
    Heap allocation sum: 124987500
    Stackalloc sum: 124987500
```

## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

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

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)