How should I concatenate strings?

2019-01-14 16:09发布

Are there differences between these examples? Which should I use in which case?

var str1 = "abc" + dynamicString + dynamicString2;

var str2 = String.Format("abc{0}{1}", dynamicString, dynamicString2);

var str3 = new StringBuilder("abc").
    Append(dynamicString).
    Append(dynamicString2).
    ToString();

var str4 = String.Concat("abc", dynamicString, dynamicString2);

There are similar questions:

This question is asking about what happens in each case, what will be the real output of those examples? What are the differences about them? Where should I use them in which case?

9条回答
我命由我不由天
2楼-- · 2019-01-14 16:58

@ Jerod Houghtelling Answer

Actually String.Format uses a StringBuilder behind the scenes (use reflecton on String.Format if you want)

I agree with the following answer in general

查看更多
孤傲高冷的网名
3楼-- · 2019-01-14 17:01

@Xander. I believe you man. However my code shows sb is faster than string.format.

Beat this:

Stopwatch sw = new Stopwatch();
sw.Start();

for (int i = 0; i < 10000; i++)
{
    string r = string.Format("ABC{0}{1}{2}", i, i-10, 
        "dasdkadlkdjakdljadlkjdlkadjalkdj");
}

sw.Stop();
Console.WriteLine("string.format: " + sw.ElapsedTicks);

sw.Reset();
sw.Start();
for (int i = 0; i < 10000; i++)
{
    StringBuilder sb = new StringBuilder();
    string r = sb.AppendFormat("ABC{0}{1}{2}", i, i - 10,
        "dasdkadlkdjakdljadlkjdlkadjalkdj").ToString();
}

sw.Stop();
Console.WriteLine("AppendFormat: " + sw.ElapsedTicks);
查看更多
我只想做你的唯一
4楼-- · 2019-01-14 17:02

It's important to understand that strings are immutable, they don't change. So ANY time that you change, add, modify, or whatever a string - it is going to create a new 'version' of the string in memory, then give the old version up for garbage collection. So something like this:

string output = firstName.ToUpper().ToLower() + "test";

This is going to create a string (for output), then create THREE other strings in memory (one for: ToUpper(), ToLower()'s output, and then one for the concatenation of "test").

So unless you use StringBuilder or string.Format, anything else you do is going to create extra instances of your string in memory. This is of course an issue inside of a loop where you could end up with hundreds or thousands of extra strings. Hope that helps

查看更多
登录 后发表回答