How should I concatenate strings?

半腔热情 提交于 2019-12-28 05:58:35

问题


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:

  • Difference in String concatenation which only asks about the + operator, and it's not even mentioned in the answer that it is converted to String.Concat
  • What's the best string concatenation method which is not really related to my question, where it is asking for the best, and not a comparation of the possible ways to concatenate a string and their outputs, as this question does.

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?


回答1:


As long as you are not deailing with very many (100+) strings or with very large (Length > 10000) strings, the only criterion is readability.

For problems of this size, use the +. That + overload was added to the string class for readability.

Use string.Format() for more complicated compositions and when substitutions or formatting are required.

Use a StringBuilder when combining many pieces (hundreds or more) or very large pieces (length >> 1000). StringBuilder has no readability features, it's just there for performance.




回答2:


Gathering information from all the answers it turns out to behave like this:

The + operator is the same as the String.Concat, this could be used on small concatenations outside a loop, can be used on small tasks.

In compilation time, the + operator generate a single string if they are static, while the String.Concat generates the expression str = str1 + str2; even if they are static.

String.Format is the same as StringBuilder.. (example 3) except that the String.Format does a validation of params and instantiate the internal StringBuilder with the length of the parameters.

String.Format should be used when format string is needed, and to concat simple strings.

StringBuilder should be used when you need to concatenate big strings or in a loop.




回答3:


Use the + operator in your scenario.

I would only use the String.Format() method when you have a mix of variable and static data to hold in your string. For example:

string result=String.Format(
    "Today {0} scored {1} {2} and {3} points against {4}",..);

//looks nicer than
string result = "Today " + playerName + " scored " + goalCount + " " + 
    scoreType + " and " + pointCount + " against " + opposingTeam;

I don't see the point of using a StringBuilder, since you're already dealing with three string literals.

I personally only use Concat when dealing with a String array.




回答4:


My rule of thumb is to use String.Format if you are doing a relatively small amount of concatination (<100) and StringBuilder for times where the concatination is going to be large or is potentially going to be large. I use String.Join if I have an array and there isn't any formatting needed.

You can also use the Aggregate function in LINQ if you have an enumerable collection: http://msdn.microsoft.com/en-us/library/bb548651.aspx




回答5:


@ 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




回答6:


@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);



回答7:


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




回答8:


It is important to remember that strings do not behave like regular objets. Take the following code:

string s3 = "Hello ";
string s3 += "World";

This piece of code will create a new string on the heap and place "Hello" into it. Your string object on the stack will then point to it (just like a regular object).

Line 2 will then creatre a second string on the heap "Hello World" and point the object on the stack to it. The initial stack allocation still stands until the garbage collector is called.

So....if you have a load of these calls before the garbage collector is called you could be wasting a lot of memory.




回答9:


var str3 = new StringBuilder
    .AppendFormat("abc{0}{1}", dynamicString, dynamicString2).ToString(); 

the code above is the fastest. so use if you want it fast. use anything else if you dont care.



来源:https://stackoverflow.com/questions/3102806/how-should-i-concatenate-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!