c# - Where are strings more useful than a StringBuilder? -


A lot of questions have been asked about the differences between the string and string builder, and most people suggest that the string Builder is faster than string, I want to know that string builder is very good, so why is the string? Besides, can some body give me an example where string string can be more useful than builder?

It is not the case whose cases are more useful ...

A String is a string - one or more letters next to each if you string in any way changes If you want, it will only create more strings because they are .

A stringbinder is a class that creates a string. It provides a means to create many radiant strings in memory without creating them. The end result will always be a string .

Do not do that

  string s = "my string"; S + = "It's a little longer";  

or

  s = s + "is longer longer";  

This will create a 5 string in memory (in fact, see below).

Do this:

  stringbuilder sb = new stringbiller (); Sb.Append ("My String"); Sb.Append ("It's a little longer"); Sb.Append ("now is again now"); String s = sb.ToString ();  

This will create a 1 string in memory (again, see below).

You can:

  string s = "it is now" + date time.Now + ".";  

This creates the 1 string in memory only.

As a side-note, make StringBuilder anyway take certain memory as a rule of thumb:

    < Li> If you are aligning the string in a loop, always use stringbuilder .
  • A stringbuilder If you add more than 4 times the string.

Comments