string is immutable and stringbuilder is mutable

前端 未结 8 1329
轻奢々
轻奢々 2020-12-06 08:38

can any one explain with examples


Related Discussion: Most efficient way to concatenate strings?

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 09:15

    A string object is immutable, once created, it cannot be changed

    string str;
    //new string object constructed. str= new string("string1");
    str="string1";
    //again new object will be constructed str=new string("string1string2");
    str=str+"string2" 
    since a new object is created for every assignment, there is an overhead.
    

    However, string builder class provides an efficient way to repeatedly append bits of string to already constructed object.

    StringBuilder str=new StringBuilder();
    str.Append("string1");
    str.Append("string2");
    

    The performance difference will be too small to compare on fewer assignment and concatenation operation, but there is significance performance gain by switching from string to stringbuilder if we have more of these string operations.

提交回复
热议问题