Introduction to the difference between

The disadvantage of String is that memory must be reallocated every time the contents of a String variable change. If you think about it, if you create a loop that iterates 100,000 times, and each iteration concatenates a character to a string, you’ll have 100,000 strings in memory, each string just associated with the previous string but different by one character, the performance impact is huge. StringBuilder solves these problems by allocating a cache, that is, a workspace, to which the StringBuilder class’s methods apply. This includes adding, deleting, removing, inserting and replacing characters and so on. After execution, the ToString method is called to convert the contents of the workspace into a string for easy assignment to a string variable. So StringBuilder will improve some performance.

Features of a String object:

1. It is a reference type that allocates memory on the heap

2. A new instance is created during the operation

3. Once generated, strings are Immutable.

4. Define the equality operators (== and! =) is used to compare String values (not references)

Strings are immutable objects in.net. Once you create a String and assign a value to it, it cannot be changed, meaning you cannot change the value of a String. This may sound strange at first, but you might immediately think of string concatenation. Can’t we change strings, too? Take a look at the following code:

public static void Main(string[] args)
{
        string s ="abc";
        Console.WriteLine(s);  / / output ABC
        s = s +"def"; 
        Console.WriteLine(s);  //def 
        Console.Read(); 
}
Copy the code

It looks as if we have changed the value of s from “ABC” to “abcdef”, but there is no change. string s = “abc”; It creates a String object that has a value of “ABC”, s refers to its address in memory, s += “def”; I’m creating a new String object that has the value “abcdef”, and s points to the new memory address. There are actually two string objects in the heap at this point, and even though we only refer to one of them, the string “ABC” still resides in memory.

As mentioned earlier, String is a reference type. If we create multiple String objects with the same value, it should point to the same address in memory. In other words, when we create a string object s with a value of “ABC”, when we create a string object STR with a value of “ABC” it does not allocate a chunk of memory, but points directly to the address of S in memory. This ensures efficient use of memory. Look at the following code:

public static void Main(string[] args)
{
    string s = "abc";
    Console.WriteLine(s);  / / output ABC
    Add(s);   // Call the following method
    Console.WriteLine(s);  / / output def
    Console.Read();
}
public static void Add(string str)
{
    str = "def";
}
// Change the method argument, use the ref keyword,,
public static void Main(string[] args)
{
    string s = "abc";
    Console.WriteLine(s);  / / output ABC
    Add(ref s);
    Console.WriteLine(s);  //abcdef
    Console.Read();
}
public static void Add(ref string str) {
    str = "def";
}
Copy the code

Set the StringBuilder capacity

The StringBuilder object is a dynamic string that can be extended by the number of characters it sets. In addition, you can set a maximum length, which is called the Capacity of the StringBuilder object.

The point of setting a capacity for StringBuilder is that when a StringBuilder string is modified, it does not reallocate space until its actual character length (that is, the number of characters the string already has) reaches its capacity. When the StringBuilder reaches its capacity, it is automatically left unset. By default, The StringBuilder starts with 16 characters. There are two ways to set the capacity of a StringBuilder object.

1. Use constructors

The StringBuilder constructor can take a capacity parameter, for example, declare a StringBuilder object sB2 and set its capacity to 100.

// Use the constructor

 StringBuilder Mysb1=new StringBuilder(“Hello”,100);

2. Use the Capacity read/write attribute

The Capacity property specifies the Capacity of a StringBuilder object. For example, the following statement begins with a StringBuilder object sb3 and uses the Capacity property to set its Capacity to 100.

// Use the Capacity attribute

 StringBuilder Mysb2=new StringBuilder(“Hello”);

 sb3.Capacity=100;

Common methods of StirngBuilder

1: the StringBuilder. Append (). Appends the content to the end of the current StringBuilder string.

public static void Main(string[] args){ 
   StringBuilder Mysb = new StringBuilder("abc:");    
    Mysb.Append(" bcd");    
    Console.WriteLine(Mysb);  // output: ABC :def
    Console.Read();
}
Copy the code

2: the StringBuilder. AppendFormat (). Replaces the symbol to be passed by the string with formatted text.

static void Main(string[] args)
{
    int Mysb1 = 100;
    StringBuilder Mysb2 = new StringBuilder("You owe me:");
    Mysb2.AppendFormat("{0:C}", Mysb1);
    Console.WriteLine(Mysb2);  // Output: You owe me ¥100
    Console.Read();
}
Copy the code

3: the StringBuilder. Insert (int, string).

Inserts strings and objects into the specified position of the current StringBuilder string. Use this method to insert a word into the sixth position of the StringBuilder.

static void Main(string[] args)
{
      StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
      MyStringBuilder.Insert(6."Insert");
      Console.WriteLine(MyStringBuilder);  // The output is: Hello insert World!
      Console.Read();
}
Copy the code

4: StringBuilder. Remove (p, n). Removes the specified character from the current StringBuilder object, that is, n characters from position P

static void Main(string[] args)
{
      StringBuilder Mysb = new StringBuilder("Hello World!");
      Mysb.Remove(2.2);
      Console.WriteLine(MyStringBuilder);  // Output is: heo world
      Console.Read();
}
Copy the code

5: StringBuilder. Replace (a, b). This is the substitution of b for the specified string a, where a and B are both characters or strings.

static void Main(string[] args)
{
     string a = "aaa.Baidu.com";
     string b = a.Replace('a'.'w');
     Console.WriteLine(b);     / / output: www.Baidu.com
}
Copy the code

In fact, when we create a StringBuilder object, the.NET runtime allocates a cache area in memory for the current object to reserve space for string operations. When using the StringBuilder class, it is best to set the capacity to the maximum possible string length to ensure that StringBuilder does not need to allocate memory twice. If the character size exceeds the maximum capacity set, the.NET runtime automatically allocates memory and doubles it.

For us.net programmers, StringBuilder differs from String in that StringBuilder displays the size of the allocated memory, whereas String can only be allocated enough memory by the system based on the size of the String you initialize.

So, when it comes to manipulating strings frequently, between String and StringBuilder, we should choose StringBuilder.