Difference between string and StringBuilder in c# -


I want to know the difference between string and StringBuilder And some examples are also required to understand.

A string example is unchanged, after you create it you do not change it Can. Any action that appears to change the string, returns a new example instead:

  string foo = "Foo"; // replaces the old one string bar = foo.Replace ('o', 'a') instead returns a new string instance; String baz = foo + "bar"; There are some good properties in irreversible things, such as they can be used in threads without fear of synchronization problems or you can straighten out your personal backing field directly without any fear. They change the objects that should not be changed (see AER or mutable lists, which should be copied before returning if they are not often desired). But when used casually, they can cause serious performance problems (almost anything - if you need an example from a language that is proud of the speed of execution see the string manipulation function of C.).  

Unstable string, as if you make a piece-target or where you change a lot of things, then you will need the stringbiller The buffer of may be changed, for the most part, the display effect is if you want a temporary string and instead of using a normal string example , You create and destroy a lot of objects As well as to be useless with, while a StringBuilder for example will change itself, will negate the need of many new objects.

Simple Examples: The following several programmers will anticipate pain:

  string s = string.Empty; For (i = 0; i  

You will prepare 2001 strings here, 2000 of which are thrown. Same example using StringBuilder:

  stringbilder sb = new stringbilder (); For (i = 0; i <1000; i ++) {sb.Append (i); Sb.Append (''); }  

It should take very little stress on memory allocation: -)

However it should be noted, when it comes to the C # compiler string, For example, the following line

  string foo = "abc" + "def" + "efg" + "hij";  

will be included by the compiler, leaving only one string on the runtime. Similarly, lines like

  string foo = a + b + c + d + e + f; The  

string will be rewritten in foo = string.Concat (a, b, c, d, e, f);

So you do not have to pay for five irrelevant connections, which would be a simple way of dealing with this. It will not save you in the upper ends (unless the compiler rejects the loop, but I think that only JIT can actually do this and can not bet on it better.)


Comments