How should I concatenate strings?

前端 未结 9 1420
不知归路
不知归路 2020-12-06 00:43

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

var str1 = \"abc\" + dynamicString + dynamicString2;

var str2 = String.Form         


        
相关标签:
9条回答
  • 2020-12-06 01:24

    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

    0 讨论(0)
  • 2020-12-06 01:26
    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.

    0 讨论(0)
  • 2020-12-06 01:30

    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.

    0 讨论(0)
提交回复
热议问题