Skip to main content

Command Palette

Search for a command to run...

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.

Published
2 min read
Day 19 of 30-Day .NET Challenge: Stack vs. Heap Allocation
S

Hi there 👋 I'm Sukhpinder Singh, a passionate self-taught .Net developer from India. Worked on 10+ projects for SQL database design. Developed and maintained over 20 .NET websites with 100% client satisfaction.

Skills C# | Microsoft Certified | Medium Blogger | .Net Core | Xamarin | ASP.Net | Angular


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
Edit descriptionsinghsukhpinder.medium.com

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());
}

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}";
}

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}";
    }
}

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

Console output

User0
User0

Complete Code on GitHub

GitHub — ssukhpinder/30DayChallenge.Net
Contribute to ssukhpinder/30DayChallenge.Net development by creating an account on GitHub.github.com


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

30 Day C# Challenge

Part 12 of 30

The series consists of a 30-day code challenge where I'll be diving deep into a different C# concept every single day. 🌟 I'll also be sharing my learnings and insights through engaging articles.

Up next

Day 18 of 30-Day .NET Challenge: AggressiveInlining Attribute

It influences the Just-In-Time (JIT) compiler’s behaviour to enhance the execution speed of critical methods.