Code Review: Constructing a StringBuilder with a capacity
Its the small things that seem to be the most generally applicable when writing code and one of those little things is the construction of a StringBuilder.
I guess most developers assume that concatenating strings is not very efficient, because they are immutable it means a lot of copying and memory allocation behind the scenes. One of the advantages that “modern” programming languages such as Java and the .NET family proclaimed over their predecessors was a StringBuilder. This made string concatenation much more efficient, so I guess like a lot of other developers I made a mental note to replace this
string str = "The items are called: "; foreach Item thisItem in allItems { str += thisItem.Name + " "; } return str;
with this
StringBuilder str = new StringBuilder(); str.Append("The items are called: "); foreach Item thisItem in allItems { str.Append(thisItem.Name); str.Append(" "); } return str.ToString();
Well it turns out that if we do that its actually not really any more efficient. The StringBuilder usually has a small initial size and behind the scenes it is doing pretty much the same thing as concatenation, it needs to reallocate memory each time it grows. A better replacement is this
StringBuilder str = new StringBuilder(1000); str.Append("The items are called: "); foreach Item thisItem in allItems { str.Append(thisItem.Name); str.Append(" "); } return str.ToString();
The thing is even if I don’t know the best initial allocation for the StringBuilder I have a guess because a guessed value will be better than leaving it as zero.
I do know that there is some debate about the most efficient method of concatenating strings and this article suggests that String.Join is more efficient. I am not suggesting using any one method in preference to any other what I am suggesting is that when StringBuilder is used it should be given an initial capacity.