Memory usage of concatenating strings using interpolated vs “+” operator

后端 未结 4 923
无人共我
无人共我 2021-01-01 15:36

I see the benefit of using interpolated strings, in terms of readability:

string myString = $\"Hello { person.FirstName } { person.LastName }!\"
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 15:50

    Strings are immutable. That means they can't be changed.

    When you concatenate strings with a + sign, you end up creating multiple strings to get to the final string.

    When you use the interpolation method (or StringBuilder), the .NET runtime optimizes your string use, so it (in theory) has better memory usage.

    All that being said, it often depends on WHAT you are doing, and HOW OFTEN you are doing it.

    One set of concatenations doesn't offer a lot of performance/memory improvements.

    Doing those concatenations in a loop can have a lot of improvement.

提交回复
热议问题