Memory consumption when chaining string methods

202 views Asked by At

I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string?

If it is true, what is the best practice to do too many manipulations on a string using chaining methods?

3

There are 3 answers

2
poke On BEST ANSWER

Is it true that when you chain string functions, every function instantiates a new string?

In general, yes. Every function that returns a modified string does so by creating a new string object that contains the full new string which is stored separately from the original string.

There are certain ways to avoid this, especially using StringBuilder when you create the string from various parts. But in general, it’s difficult to say how you could make something better without creating multiple in-between string objects.

But as bad as this sounds, it usually isn’t a big problem: While it can be expensive, extraneous string objects because of string manipulations are very rarely a source of bad performance. Unless you are doing high-performance stuff with strings, you can probably ignore the fact that you keep creating new objects which are then thrown away. If you have doubts later, you can always profile your code to find out if it really matters or not.

0
Alecu On

We used in our models which were bound to the UI a special method to get a unique id for that object. The method would concatenate some strings using the + operator.

It ended up being called 10000 times or more in a second sometimes which slowed down the entire application when loading new data. It was a serious bottleneck when first loading some screens in the application. So I guess if you are not calling the code which use string operations at least a couple of thousand times a second then you are okay.

There is also the string.Format method that is a couple of times faster in the long run.

2
Sayse On

I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string?

Yes, strings are immutable and thus they cannot be changed - at all. But not every function will instantiate a new string as some may be susceptible to string interning (strings of the same text can (but not always!) inhabit the same memory space)

If it is true, what is the best practice How to do too many manipulations on a string?

The most two common methods used are either to build a string up first using StringBuilder or via a String.Format