Use StringBuilder on string Refactor! Pro feature

One of the wellcome refactoring features of [DX] Refactor! Pro is “replace string with StringBuilder”. Why would you want to do that? String building into a string variable is slow because each time you change the value of string variable the memory for new value is allocated, new value is stored into this new memory place and old memory block is released for garbage collection. So, if you have a bunch of string modifications, such as building a text, you should avoid using string variable and instead use StringBuilder class that deals with memory much more gently (note that if you have few modifications string variable is still a better option). That’s why Use StringBuilder refactoring comes handy. Imagine this piece of immaginary code that happens to exist here and there:

int[] list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; string concatenated = string.Empty; foreach (int item in list) { if (concatenated.Length > 0) concatenated += ", "; concatenated += item.ToString(); } return c

If the number of items would be greater this code will become relatively sluggish to execute. Obviously there is a need of StringBuilder but instead of manually rewritting the code you can do this: select the code and press Refactor! key, pick Use StringBuilder: concatenated from Refactor! menu:

Refactor! will preview what changes it will do to replace the string with StringBuilder. Confirm the change and here is what you’ll get:

int[] list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; StringBuilder concatenatedBuilder = new StringBuilder(); foreach (int item in list) { if (concatenatedBuilder.Length > 0) concatenatedBuilder.Append(", "); concatenatedBuilder.Append(item.ToString()); } return concatenatedBuilder.ToString();

Needless to say that no coding was required and the code will perform much better, specially with bigger lists. Cool, eh.

Leave a Reply