Improve c # code method – (1) operation string


Operate strings correctly

String is a data type that is used frequently.
If it is used carelessly, it will pay for the extra performance cost of a string operation.
This paper discusses how to operate strings correctly from the following aspects:

1. Make sure to pack as little as possible and avoid writing unnecessary packing codes as much as possible

string str1 = "str1" + 8;               // The runtime completes a boxing action
string str2 = "str2" + 8.ToString();    // There is no packing behavior and the efficiency is higher

2. Avoid allocating extra memory space

In CLR, the string class is a special reference type. Once the string object is assigned, it cannot be changed.
When running, a new string object will be created in memory by calling any method in the system. String class or performing any operation (such as “=” assignment, “+” splicing),
To allocate new memory space for the new object.

private void Method()
    string str1 = "abc";               
    str1 = "123" + str1 + "456";    
    //The above code creates three string objects and executes the string. Concat method once, which will bring extra runtime overhead.

3. Use StringBuilder class

The StringBuilder type provided by Microsoft can make up for the deficiency of string.
StringBuilder doesn’t recreate a string object. Its efficiency comes from allocating memory in an unmanaged way in advance.
If StringBuilder does not have a predefined length, the default allocated length is 16.
When the character length of StringBuilder is less than or equal to 16, StringBuilder will not reallocate memory;
When the length is greater than 16 and less than 32, StringBuilder will reallocate the memory to make it a multiple of 16.
The length specified by StringBuilder should be appropriate. If it is too small, it needs to allocate memory frequently. If it is too large, it will waste space.

public static void Method1() 
    StringBuilder sb = new StringBuilder ("me");
    Sb. Append ("yes");
    Sb. Append ("one");
    Sb. Append ("procedure");
    Sb. Append ("order");
    Sb. Append ("member");
    string str = sb.ToString();

4. Use the string. Format method

The string. Format method uses StringBuilder internally to format strings, which can simplify the operation of StringBuilder.

public static void Method2()
    String STR = string. Format ("{0} {1} {2} {3}", "me", "yes", "one", "programmer");

5. Use interpolation string$

The interpolation string $is the syntax sugar of string. Format, which can express parameters more intuitively.

public static void Method3()
    Var name = Xiaoming;
    var year = 20;
    Var job = programmer;
    Var STR = $"{name} is {year} and {job}.";
    //The year in the previous interpolation string is of int type, which will cause boxing operation and affect performance
    //Can be optimized as: VAR STR = $"{name} age is {year. Tostring()}, work is {job}.";