String vs. StringBuilder

后端 未结 24 1261
眼角桃花
眼角桃花 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:46

    StringBuilder is preferable IF you are doing multiple loops, or forks in your code pass... however, for PURE performance, if you can get away with a SINGLE string declaration, then that is much more performant.

    For example:

    string myString = "Some stuff" + var1 + " more stuff"
                      + var2 + " other stuff" .... etc... etc...;
    

    is more performant than

    StringBuilder sb = new StringBuilder();
    sb.Append("Some Stuff");
    sb.Append(var1);
    sb.Append(" more stuff");
    sb.Append(var2);
    sb.Append("other stuff");
    // etc.. etc.. etc..
    

    In this case, StringBuild could be considered more maintainable, but is not more performant than the single string declaration.

    9 times out of 10 though... use the string builder.

    On a side note: string + var is also more performant that the string.Format approach (generally) that uses a StringBuilder internally (when in doubt... check reflector!)

提交回复
热议问题