Day 19 of 30-Day .NET Challenge: Stack vs. Heap Allocation
Tags: dotnet, csharp, webdev, programming
Published: 2024-04-07 07:32:00

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](https://singhsukhpinder.medium.com/list/52a751260fe1)

## 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.
```csharp
    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.
```csharp
    private string GetUserName(int index)
    {
        // Efficient: Avoids unnecessary heap allocation
        return $"User{index}";
    }
```
Create another class named StackVsHeap and add the following code snippet
```csharp
    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
```csharp
    #region Day 19: Stack vs. Heap Allocation
    static string ExecuteDay19()
    {
        StackVsHeap.InefficientMethod(0);
        StackVsHeap.EfficientMethod(0);
        return "Executed Day 19 successfully..!!";
    }
    
    #endregion
```
Console output
```csharp
    User0
    User0
```
## 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)