DEV Community

Cover image for Day 19 of 30-Day .NET Challenge: Stack vs. Heap Allocation
Sukhpinder Singh
Sukhpinder Singh

Posted on

Day 19 of 30-Day .NET Challenge: Stack vs. Heap Allocation

The article demonstrates the idea of memory allocations to be used for vibrant and high-performance applications.

Introduction

The article demonstrates the idea of memory allocations to be used for vibrant and high-performance applications. There are majorly two types of memory allocation i.e. stack vs heap which plays a role in how your application uses resources and, further, how fast and responsive the application can be.

Learning Objectives

  • What is heap allocation

  • What is stack allocation

  • Limiting the Use of Heap-Allocated Objects

Prerequisites for Developers

  • Basic understanding of C# programming language.

30 Day .Net Challenge

Getting Started

What is heap allocation?

The heap memory is primarily used for dynamic allocation, where the size and lifespan of the allocation are not predicted at the compile time. Reference types instances (like objects and arrays in C#) are stored on the heap.

What is stack allocation?

The stack is a section of memory that stores value types and pointers to heap-allocated objects. Memory allocation on the stack is fast because it involves merely moving the stack pointer.

Limiting the Use of Heap-Allocated Objects

Whenever possible, opt for stack allocation or the use of value types to minimize the need for garbage collection.

Inefficient Heap Allocation

The following method creates a new string object on the heap each time the method is called, which will call the Garbage Collection each time too.

    private string GetUserName(int index)
    {
        // Inefficient: Creates a new string object on the heap
        return new string($"User{index}".ToCharArray());
    }
Enter fullscreen mode Exit fullscreen mode

Efficient Allocation

By returning the interpolated string without newkeyword avoids unnecessary heap allocation and reduces the impact on garbage collection, which leads to better performance.

    private string GetUserName(int index)
    {
        // Efficient: Avoids unnecessary heap allocation
        return $"User{index}";
    }
Enter fullscreen mode Exit fullscreen mode

Create another class named StackVsHeap and add the following code snippet

    public static class StackVsHeap
    {
        public static string InefficientMethod(int index)
        {
            // Inefficient: Creates a new string object on the heap
            return new string($"User{index}".ToCharArray());
        }

        public static string EfficientMethod(int index)
        {
            // Efficient: Avoids unnecessary heap allocation
            return $"User{index}";
        }
    }
Enter fullscreen mode Exit fullscreen mode

Execute from the main method as follows

    #region Day 19: Stack vs. Heap Allocation
    static string ExecuteDay19()
    {
        StackVsHeap.InefficientMethod(0);
        StackVsHeap.EfficientMethod(0);
        return "Executed Day 19 successfully..!!";
    }

    #endregion
Enter fullscreen mode Exit fullscreen mode

Console output

    User0
    User0
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

Top comments (0)