C# simple performance improvement

1、String Split()

  • In C#, there are 10 Split()overloaded methods

Split()

  • General usage
static void SplitChar()
{
    
    
    var str = "Hello|World";
    // 实例化秒表对象
    var s1 = new Stopwatch();
    s1.Start();
    _ = str.Split('|');
    Console.WriteLine($"SplitChar ElapsedTicks:{s1.ElapsedTicks}");
}
  • Optimized writingCreate an array of characters and pass them as parameters to the Split()method
static void SplitCharArray()
{
    
    
    var str = "Hello|World";
    // 实例化秒表对象
    var s1 = new Stopwatch();
    s1.Start();
    _ = str.Split(new char[] {
    
     '|' });
    Console.WriteLine($"SplitCharArray ElapsedTicks:{s1.ElapsedTicks}");
}

The test results, it is obvious that the efficiency of using character arrays is much higher
Test Results

2、String Equals()

  • Check strwhether the value of the variable is equal to the string “Akshay”, and, don’t know why, strthe value isnull
static void Equals1()
{
    
    
    try
    {
    
    
        string str = null;
        Console.WriteLine(str.Equals("Hello World") ? "IF" : "ELSE");
    }
    catch (Exception ex)
    {
    
    
        Console.WriteLine(ex.Message);
    }

}

The above writing, our program throws aNull referenceabnormal
Test Results

  • strThe Equals()method not used , but “Akshay”the Equals()method used
static void Equals2()
{
    
    
    try
    {
    
    
        string str = null;
        Console.WriteLine("Hello World".Equals(str) ? "IF" : "ELSE");
    }
    catch (Exception ex)
    {
    
    
        Console.WriteLine(ex.Message);
    }
}

After changing our thinking, our program outputs the result we defined
Test Results

3、Adding Strings()

  • Benchmark string interpolation, string format, string concat, and string builder
static void AddStrings()
{
    
    
    string str = "Hello";
    string str1 = "World";
    var s1 = new Stopwatch();

    //String Interploation
    s1.Start();
    _ = $"{str} {str1} is an author";
    Console.WriteLine($"String Interpolation {s1.ElapsedTicks}");

    //String Format
    s1.Restart();
    _ = string.Format("{0},{1} is an author", str, str1);
    Console.WriteLine($"String Format {s1.ElapsedTicks}");

    //String Concat
    s1.Restart();
    _ = string.Concat(str, str1, " is an auther");

    Console.WriteLine($"String Concat {s1.ElapsedTicks}");

    //StringBuilder
    s1.Restart();
    StringBuilder sb = new StringBuilder();
    sb.Append(str);
    sb.Append(str1);
    sb.Append(" is an auther");
    _ = sb.ToString();
    Console.WriteLine($"StringBuilder {s1.ElapsedTicks}");
}

Four different methods to add stitching together two strings, four methods string.Concat()when used happened
The test results suggest that the use string.Concat()for string concatenation method
Test Results

4、List.Count() Vs List.Any() Vs List.Count

  • Before iterating, use List.Count()methods to check if the lib has data or if it is empty. Here compare List.Count()and List.Any()method execution time
static void ListCountAndAny()
{
    
    
    var watch = new Stopwatch();
    var strs = new List<string>()
    {
    
    
        "Hello",
        "World",
        "CSahrp",
        "Years"
    };

    watch.Start();
    if (strs.Count() > 0) {
    
     }
    Console.WriteLine($"List.Count() {watch.Elapsed}");

    watch.Restart();
    if (strs.Any()) {
    
     }
    Console.WriteLine($"List.Any() {watch.Elapsed}");

    watch.Restart();
    if (strs.Count > 0) {
    
     }
    Console.WriteLine($"List.Count {watch.Elapsed}");
}

Count()Methods Any()save time than methods. But using Countattributes directly takes less time
Test Results

5、Array Length

  • Developers tend to use Array.Lengthas iteration conditions in for loops , but what we need to know is that Lengthattributes are called for each iteration .It is better to store it in a variable and use that variable as the iteration condition

The length of the array is directly used as the iteration condition

static void ArrayLengthInLoop()
{
    
    
    var watch = new Stopwatch();
    string[] names = new[] {
    
     "Akshay", "Patel", "Panth" };
    watch.Start();
    for (int i = 0; i < names.Length; i++) {
    
     }
    Console.WriteLine($"Array.Length in the Loop: {watch.Elapsed}");
}

The length of the array, stored in a variable, and use the variable as the iteration condition

static void ArrayLengthInVariable()
{
    
    
    var watch = new Stopwatch();
    string[] names = new[] {
    
     "Akshay", "Patel", "Panth" };
    watch.Start();
    int k = names.Length;
    for (int i = 0; i < k; i++) {
    
     }
    Console.WriteLine($"Array.Length in a Variable: {watch.Elapsed}");
}

Save the time to obtain the length of the array except for the first time, and improve a certain degree of efficiency
Test Results
There is a certain error in the test result, just refer to it

Guess you like

Origin blog.csdn.net/qq_43562262/article/details/112076920