The article demonstrates the idea of using memory allocations 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.
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.
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.
Whenever possible, opt for stack allocation or the use of value types to minimize the need for garbage collection.
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());
}
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
GitHub — ssukhpinder/30DayChallenge.Net
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