C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The StringBuilder combines the strings into a single object, reducing the workload of the garbage collector.
Tip: This shows the memory savings that can be attained by changing the representation of your data models.
GetList: This method generates a List containing 100,000 random strings. All of the strings in the List will be allocated separately on the managed heap.
GetBuilder: This generates a StringBuilder containing 100,000 random strings concatenated.
C# program that tests StringBuilder memory usage
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Program
{
static StringBuilder _builder;
static List<string> _list;
static void Main()
{
//
// Get start memory.
//
long bytes1 = GC.GetTotalMemory(true);
//
// Allocate a list or StringBuilder of many strings.
// ... Comment out one of these lines to one method.
//
_list = GetList();
_builder = GetBuilder();
//
// Compute memory usage.
//
long bytes2 = GC.GetTotalMemory(true);
Console.WriteLine(bytes2 - bytes1);
}
static List<string> GetList() // Allocate list of strings
{
List<string> list = new List<string>();
for (int i = 0; i < 100000; i++)
{
string value = Path.GetRandomFileName();
list.Add(value);
}
return list;
}
static 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;
}
}
Output
List: 4.7 MB
StringBuilder: 4.0 MB
Therefore: The StringBuilder version of the program saves the trouble of managing 100,000 strings.
And: When the program uses the GetStringBuilder method only, it allocates 4,194,456 bytes on the heap.
Thus: The StringBuilder representation of the data saves 729,996 bytes or 713 KB.