I have an List<string> that I am iterating through and splitting on each item then adding it to a StringBuilder.
foreach(string part in List)
{
StringBuilder.Append(part.Split(':')[1] + " ");
}
So my question is how many strings are created by doing this split? All of the splits are going to produce two items. So… I was thinking that it will create a string[2] and then an empty string. But, does it then create the concatenation of the string[1] + " " and then add it to the StringBuilder or is this optimized?
The code is actually equivalent to this:
So yes, an additional
string, representing the concatenation of the second part of the split and the empty string will be created.Including the original
string, you also have the two created by the call toSplit(), and a reference to the literal string" ", which will be loaded from the assembly metadata.You can save yourself the call to
Concat()by justAppending the split result and the empty string sequentially:Note that if you are only using string literals, then the compiler will make one optimzation for you:
is actually compiled to