paint-brush
How to Use Stackalloc: Day 28 of 30-Day .NET Challengeby@ssukhpinder
212 reads

How to Use Stackalloc: Day 28 of 30-Day .NET Challenge

by Sukhpinder SinghApril 19th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Learn to enhance your performance with stackalloc in C. Discover a better approach on Day 28 of our 30-Day.NET Challenge. 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 loops30 Day.Net Challenge(https://singhsukhpinder.medium.com/list/52a751260fe1)
featured image - How to Use Stackalloc: Day 28 of 30-Day .NET Challenge
Sukhpinder Singh HackerNoon profile picture

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

Getting Started

Understanding What Is stackalloc

Stackalloc is a reserved keyword in C# that 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.

    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

    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

    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 Drom the Main Method as Follows

    #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

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