What string concatenation method to use for N number of iterations?

If I want to concatenate string N the number of times, which method should I use?

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 can be called with a "time" set to 5 or 5000. Which method should I use?

string.join? StringBuilder? Just a standard string. Concat?

A similar function will be implemented in the commercial library, so I really need an β€œoptimal” way to do this.

+3
source share
4 answers
    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();
    }
+8
source

Stringbuilder ofcourse. , , .

. .

+5

StringBuilder.

"result + = result;"

, .

StringBuilder, .

+2

, - , .

, ( + = ) , .

, (, 50 ), , .

, , " ", , - :

if(iterations < 30)
{
    CopyWithConcatenation();
}
else
{
    CopyWithStringBuilder();
}

, , , .

, StringBuilder "" , ( ), (, , ).

, .

+2

Source: https://habr.com/ru/post/1719864/


All Articles