An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ immutable ’

As a rule of thumb, avoid using the += operation to concatenate or append to an existing string. The reasoning behind this is the System.String class is immutable (meaning unchanging). This means that when the += operation is used, instead of appending, C# is actually recreating the string. The example below is a string concatenation that should be avoided (in red):

string badExample = "This is an example of how not to append an existing string. ";
badExample += "Using += is not the way to go. ";
badExample += "Instead try the StringBuilder class!";

An alternative to the += Operation in C# is using System.Text.StringBuilder. The StringBuilder class is mutable and allows setting an initial size to prevent recreating the entire string when appending additional strings. An example on a better performing string operation is shown below (in green):

StringBuilder goodExample = new StringBuilder("This is an efficient way to build a string. ");
goodExample.Append("By using a mutable class, it prevent recreation. ");
goodExample.Append("Perfect!");

It is important to note that the initial StringBuilder character buffer is a very important aspect to efficiency. Setting a size that is too small will require the StringBuilder class to constantly recreate the entire string, making the operation no better than a += operation. However, making the StringBuilder character buffer too large will be waste on memory. Set the StringBuilder initial size by stating the character buffer on the StringBuilder initialization as demonstrated below (in orange):

StringBuilder goodExample = new StringBuilder("This is an efficent way to build a string. ", 200);

Finally, using the += operation vs StringBuilder in a single operation will not produce noticeable efficiency differences. However, it does become a more important coding practice when string concatenation operations occur in loops (such as while, for, foreach, etc). And remember to include “using System.Text;” to enable StringBuilder.