CSharp memory management

Posted by

memory management

Image credit:upload.wikimedia.org

CSharp memory management

CSharp memory management is a topic of debate for almost a decade. People often argue about the automatic memory allocation and freeing up the unused space by Garbage Collector. Then why do we need to manage memory by ourselves?
The answer to this question lies in the fact that if we use very large objects that are present in the heap , then we can become a victim of LOH or large object heap that is the heap memory fragmentation .

In some situations, the large object heap will become heavily fragmented. The amount of fragmentation is so large that the LOH uses more than twice the amount of memory than the total sum of allocated large objects.

reference: https://connect.microsoft.com/VisualStudio/feedback/details/521147/large-object-heap-fragmentation-causes-outofmemoryexception

In a more concise manner ; it would be obvious to give ten guests some rooms but due to the fact that they are large in numbers, we are allocation extra space in other rooms where they have to live.
In other sense, we might be wasting the space that the guests do not require at all. This is exactly a situation when large object requires more space than the allocated one and this space leads towards unused memory chunks. This is exactly the memory fragmentation.
This will kill the speed of our application and the Garbage collector does not do any miracle to handle LOH (mind you).

image attrib: wikipedia.org

Look at the object with yellow color. Since it has completed its life cycle but due to the fact that the memory that was dynamically allocated for it is not free. Let’s see another picture

The internal partition has some other story. The memory is allocated a fixed space and the sizes of the objects that it uses is lesser then its own size. In this scenario, the additional memory gets wasted

image credit:msdn

What is the solution?

The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a “pool” – rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object to the pool rather than destroying it; this can be done manually or automatically

ref: wiki
Following program shows how to send objects when they are required and if the objects are not created, then they will be created first. Here it is

// A class named as Program has been declared
class Program
static void Main(string[] args)
//There is an accumulator that holds newly created List of the class Program
var accumulator = new List();
//Check to see how many times our condition encourages our loop
while (true)
// start is a datetime object of class built in Datetime and it holds the current date and time
DateTime start = DateTime.Now;

//if total seconds obtained by Current datatime minus start object that holds the current date type is lesser than 15
while ((DateTime.Now – start).TotalSeconds < 15) { //accumulator variable will add new object of class Program accumulator.Add(new Program()); //thread will sleep for 1 ms Thread.Sleep(1); } //this will count the total number of objects being held by accumulator Console.WriteLine(accumulator.Count); } } }


Above program is quite easier to understand without any tension. The main theme is that; every created object held in the accumulator variable. At last; total number of objects shall be counted that are held by accumulator. Your task is to use these objects in memory efficient way and you can do it easily. All the best. Try these type of examples at least 15 times

Another way to get your memory from unused fragmentation is the use of custom Dispose() method. Here we have to use an event that gets fired when an event handler to manually free up the space from the class object. Let’s see it in action

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
static void Main(string[] args)
using (ObjectClass MyObject = new ObjectClass())
MyObject.Disposed += ObjectClass_Disposed;
Console.WriteLine(“Dispose the object?”); Console.ReadKey();
Console.WriteLine(“Finish your task”);

static void ObjectClass_Disposed(object source, EventArgs e)
Console.WriteLine(“Object has been disposed “);

class ObjectClass : IDisposable
public event EventHandler Disposed;

public void Dispose()
if (this.Disposed != null)
this.Disposed(this, EventArgs.Empty);

Facebook Comments

Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter