String or StringBuilder return values?

前端 未结 5 1779
生来不讨喜
生来不讨喜 2021-02-12 19:06

If I am building a string using a StringBuilder object in a method, would it make sense to:

Return the StringBuilder object, and let the calling code call ToString()?

5条回答
  •  时光取名叫无心
    2021-02-12 19:17

    StringBuilder is an implementation detail of your method. You should return string until it becomes a performance problem, at which point you should explore another pattern (like visitor Pattern) that can help you introduce indirection and protect you from the internal implementation decisions.

    Strings are always stored in the heap, so you will have a reference returned if the return type is string. You can't count, however, on two identical strings to have identical references. In general, it's safe to think of a string as if it were a value type even though it is actually a reference type.

提交回复
热议问题