A string
instance is immutable. You cannot change it after creating it. Any operation that appears to change a string returns a new instance:
string foo = "Foo"; // returns a new string instance instead of changing the old one string bar = foo.Replace('o', 'a'); string baz = foo + "bar"; // ditto here
Immutable objects have some good properties, for example, they can be used in streams without fear of problems with synchronization, or simply you can simply transfer your private support fields without fear that someone will change objects that they should not change (see arrays or mutable lists that often need to be copied before returning them if this is not desired). But if used carelessly, they can cause serious performance problems (just like almost anything - if you need an example from a language that prides itself on speed of execution, then look at the C string management functions).
If you need a mutable string, for example, which you produce piece by piece or where you change a lot of things, you will need StringBuilder
, which is a character buffer that you can change. This, for the most part, affects performance. If you want a variable string and instead execute it with a regular string
instance, then you will end up creating and destroying many objects unnecessarily, while the StringBuilder
instance StringBuilder
will change, which negates the need for many new objects.
A simple example: the following will cause many programmers to contract in pain:
string s = string.Empty; for (i = 0; i < 1000; i++) { s += i.ToString() + " "; }
As a result, you will create lines of 2001, 2000 of which will be thrown out. Same example using StringBuilder:
StringBuilder sb = new StringBuilder(); for (i = 0; i < 1000; i++) { sb.Append(i); sb.Append(' '); }
This should significantly reduce the load on the memory allocator :-)
It should be noted, however, that the C # compiler is smart enough when it comes to strings. For example, the following line
string foo = "abc" + "def" + "efg" + "hij";
will be combined by the compiler, leaving only one line at runtime. Similarly, strings such as
string foo = a + b + c + d + e + f;
will be rewritten to
string foo = string.Concat(a, b, c, d, e, f);
so you donβt have to pay for five meaningless concatenations that would be a naive way to handle it. This will not save you in loops, as indicated above (if the compiler does not unroll the loop, but I think that only JIT can do this and it is better not to do this).