String vs. StringBuilder

后端 未结 24 1510
眼角桃花
眼角桃花 2020-11-22 06:22

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference

24条回答
  •  春和景丽
    2020-11-22 06:48

    To clarify what Gillian said about 4 string, if you have something like this:

    string a,b,c,d;
     a = b + c + d;
    

    then it would be faster using strings and the plus operator. This is because (like Java, as Eric points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that StringBuilder also uses)

    However, if what you are doing is closer to:

    string a,b,c,d;
     a = a + b;
     a = a + c;
     a = a + d;
    

    Then you need to explicitly use a StringBuilder. .Net doesn't automatically create a StringBuilder here, because it would be pointless. At the end of each line, "a" has to be an (immutable) string, so it would have to create and dispose a StringBuilder on each line. For speed, you'd need to use the same StringBuilder until you're done building:

    string a,b,c,d;
    StringBuilder e = new StringBuilder();
     e.Append(b);
     e.Append(c);
     e.Append(d);
     a = e.ToString();
    

提交回复
热议问题