In C# String builder is used to represent a mutable string of characters. Mutable means a string that can be changed. So string objects are immutable and String Builder objects are mutable.
In practice what this means is that when you make a change to a string object that has already been instantiated, the compiler would create a new memory allocation for it. This can become very bad if you are doing something like this:
string temp = “”;
for(int i = 0; i < 10000; i++){
temp = $”{temp},{i}”;
}
The above example is something that will cause huge memory performance issues because each time the temp variable is set the it will create a new memory allocation. StringBuilder is a mutable object which when altered will edit the value in the current memory location. This will not use up free memory locations for no reason.
The above example can be re-written in the following format:
StringBuilder temp = new StringBuilder(“”);
for(int i = 0; i < 10000; i++){
temp.Append($”{temp},{i}”);
}