What string concatenation method to use for N number of iterations?
c#, string-concatenation
Solution
public static string Repeat(this string instance, int times)
{
if (times == 1 || string.IsNullOrEmpty(instance)) return instance;
if (times == 0) return "";
if (times < 0) throw new ArgumentOutOfRangeException("times");
StringBuilder sb = new StringBuilder(instance.Length * times);
for (int i = 0; i < times; i++)
sb.Append(instance);
return sb.ToString();
}
Problem
If I want to concatenate a string N number of times, which method should i prefer? Take this code as an example: ``` public static string Repeat(this string instance, int times) { var result = string.Empty; for (int i = 0; i < times; i++) result += instance; return result; } ``` This method may be invoked with "times" set to 5, or 5000. What method should I prefer to use? string.Join? Stringbuilder? Just standard string.Concat? A similar function is going to be implemented in a commercial library so I really need the "optimal" way to do this.