How should I concatenate strings?

前端 未结 9 1440
不知归路
不知归路 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

提交回复
热议问题