// Get start memory.
long bytes1 = GC.GetTotalMemory(true);
//
// Allocate memory
_list = GetList();
// or StringBuilder of many strings.
// to compare memory usage
_builder = GetBuilder();
// Get end memory
long bytes2 = GC.GetTotalMemory(true);
Console.WriteLine(bytes2 - bytes1);
The difference of memory usage with the following two use cases
List
{
List
for (int i = 0; i < 100000; i++)
{
string value = Path.GetRandomFileName();
list.Add(value);
}
return list;
}
StringBuilder GetBuilder() // Allocate StringBuilder of strings
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100000; i++)
{
string value = Path.GetRandomFileName();
builder.Append(value);
}
return builder;
}
The difference is that List is a collection of objects, when allocating memory,
GC(Garbage Collector) has to manage all the objects in addition to List it self.
On the other side, String builder is only one object that the GC need to manage.
Internally, Stringbuilder is a logical array. In above case, Using StringBuilder
will save a 1/6th space and also has good performance.
Wrap it Up
Similar to Measuring time in my previous blog, we can wrap it up into an generic instrument for measuring memory use
No comments:
Post a Comment