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.
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
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)