mshwf
mshwf

Reputation: 7449

What is more performant when using string.Format with many args: string or StringBuilder?

Does using string.Format like this:

string.Format(txt, arg0, arg1, arg2, arg3, arg4,...)

is the same as saying txt+=args; thus it creates new object every time it append a new string from the args list? and better using StringBuilder.Format ?

Upvotes: 1

Views: 130

Answers (3)

Vivek Nuna
Vivek Nuna

Reputation: 1

String.Format uses a StringBuilder in its implementation, So you cannot say which one is better.

Upvotes: 0

Steve
Steve

Reputation: 216273

My comment above means that you should test your performances in your environment. Use a Stopwatch instance, create a loop that runs over the string.Format and StringBuilder.AppendFormat for at least one hundred thousands times and then measure the value in the Stopwatch.ElapsedMilliseconds. This will roughly give you an idea of the differences.

In mine environment the two approaches are pretty identical. The difference on a 100000 loop is 2/3 milliseconds advantage for StringBuilder but the morale is:

DO NOT DO MICROOPTIMIZATIONS

(unless you have absolutely clear that the result worth the effort).

Sample:

string s1 = "Argument 1";
string s2 = "Argument 2";
string s3 = "Argument 3";
string s4 = "Argument 4";
string s5 = "Argument 5";
string s6 = "Argument 6";
string s7 = "Argument 7";
string s8 = "Argument 8";
string s9 = "Argument 9";

string result = string.Empty;
object[] data = new object[] { s1, s2, s3, s4, s5, s6, s7, s8, s9 };
Stopwatch sw = new Stopwatch();
sw.Start();
for(int x = 0; x < 100000; x++)
    result = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", data);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

StringBuilder sb = new StringBuilder();
sw = new Stopwatch();
sw.Start();
for (int x = 0; x < 100000; x++)
{
    sb.Length = 0;
    sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8}", data);
    result = sb.ToString();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

Upvotes: 1

Fabio Silva Lima
Fabio Silva Lima

Reputation: 714

If you use just string format, use string.Format. If you use a lot concatenation of strings and/or string forms, use StringBuilder.

Check this out: https://support.microsoft.com/en-us/kb/306822

Upvotes: 0

Related Questions