Friday, October 30, 2015

plus equals string concatenation

Strings are immutable in C# and whenever you appear to be modifying one you are in fact just creating a new string and putting it on the heap.

string foo = "foo";
foo += "bar";

 
 

Using a StringBuilder takes away some of the overhead of constantly growing a string by making new objects (strings) and letting old ones be dealt with by garbage collection. This is a talking point that was the fodder for interview questions ten years ago. A bigger thing to worry about in terms of optimization however would be traffic to and from the database. Don't stress the string concatenation. It probably isn't the real source of your woes. Note that strings are immutable in a weird way. They aren't value types, they are reference types that live on the heap... and yet when you "change" one the pointer for the string changes to look to the new string that is placed on the heap. This unintuitive behavior is a must for this one type given how much you use it and some of the things it has to do. It's not realistic to make a string a value type and give it a fixed-sized of memory on the stack, not when a string could contain one letter or could contain the Magna Carta. The footprint would be huge and mostly largely wasted in most scenarios.

No comments:

Post a Comment