string is immutable and stringbuilder is mutable

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

can any one explain with examples


Related Discussion: Most efficient way to concatenate strings?

8条回答
  •  既然无缘
    2020-12-06 09:30

    Immutability Of String[instance is readonly]

        string s="hi";
        //now let s be address 1000
        s+=" there"; 
        //above concatination causes creation of new instance in address location other than 1000
        //with modified value "hi there"
    

    Mutability Of stringbuilder[instance can be modified]

        StringBuilder sbr = new StringBuilder("My Favourite Programming Font is ");
        sbr.Append("Inconsolata")
    //append operation only modifies existing instance of sbr rather than creating new instance
    

    For more Interesting examples and detailed discussions Strongly recommend to Follow this link

    String Vs StringBuilder

    • String
      1. under System namespace
      2. Immutable(readonly) instance
      3. performance degrades when continuous change of value occures
      4. thread safe
    • StringBuilder(mutable string)
      1. under System.Text namespace
      2. mutable instance
      3. shows better perfomance since new changes are made to existing instance

    Descriptive article about this topic with lot of examples using ObjectIDGenerator,follow this link

    Related Stackeoverflow Question: Mutability of string when string doesn't change in C#?

提交回复
热议问题