关于性能优化技巧

一、关于Span的使用

1.Span的最大优势:切片和堆栈空间及连续性

所以在SubString这样的场景可以Span来做.

2.Span的IndexOf(string)性能不如原生,注意使用Span.IndexOf(subSpan)

 

using System;
using System.Diagnostics;

namespace SpanDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            string str = "wweidfidsjfkljsjdkljsdkjfsdlkj23423j4klsdlddssdsdsddjfl;sdjf;dsfjknxcvdjsofusd9-23432423423";
            ReadOnlySpan<char> strSapn = str.AsSpan();

            string subStr = "dsfjknxcvdjsofusd9";
           

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < 1000; i++)
            {
                var subSpan = subStr.AsSpan();
                strSapn.IndexOf(subSpan);
            }
            stopwatch.Stop();



            Console.WriteLine(stopwatch.Elapsed);

            stopwatch.Reset();


            stopwatch.Start();
            for (int i = 0; i < 1000; i++)
            {
                str.IndexOf(subStr);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);


            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }

        
    }
}

  

posted @ 2021-01-30 20:22  [秦时明月]  阅读(160)  评论(0编辑  收藏  举报