C# string 加号与StringBuilder .netCore3.1与 .netCore5.0速度测试

using System;
using System.Linq;
using System.Text;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var startTime = DateTime.Now;           
            string str = "";
            for (int i = 0; i < 100; i++)
            {
                str += i.ToString();
            }

            var ret = str;
            ret.Remove(0, 1);
            string userTime = (DateTime.Now - startTime).ToString();
            Console.WriteLine("         +:"+userTime);
            
            startTime = DateTime.Now;           
            StringBuilder str1=new StringBuilder();
            for (int i = 0; i < 100; i++)
            {
                str1.Append(i.ToString());
            }

            var ret1 = str1.ToString();
            ret1.Remove(0, 1);
            userTime = (DateTime.Now - startTime).ToString();
            Console.WriteLine("    Append:"+userTime);
            
            
            startTime = DateTime.Now;           
            string str2 = "";
            str2 ="1212312312" +
                  "312dsakjf;ak" +
                  "sldjfaisdfjiad" +
                  "sfujadspfupfffff" +
                  "ffpfpfpfpfpfpfpfpfp" +
                  "fpfpfpfpfpfpfpfpfpfpf" +
                  "pfpfpfpfpfpfpfpfpfpfpfp" +
                  "fpfpfpfpfpfpfpfpfpfp";
            var ret2 = str2.ToString();
            ret2.Remove(0, 1);
            userTime = (DateTime.Now - startTime).ToString();
            Console.WriteLine("      Fix+:"+userTime);
            
            startTime = DateTime.Now;           
            StringBuilder str3 = new StringBuilder();
            str3.Append("1212312312");
            str3.Append("312dsakjf;ak" );
            str3.Append("sldjfaisdfjiad" );
            str3.Append("sfujadspfupfffff" );
            str3.Append("ffpfpfpfpfpfpfpfpfp" );
            str3.Append("fpfpfpfpfpfpfpfpfpfpf" );
            str3.Append("pfpfpfpfpfpfpfpfpfpfpfp" );
            str3.Append("fpfpfpfpfpfpfpfpfpfp");
            var ret3 = str3.ToString();
            ret3.Remove(0, 1);
            userTime = (DateTime.Now - startTime).ToString();
            Console.WriteLine("FixBuilder:"+userTime);
            Console.ReadKey();
            
        }
    }
}

测试结果取多次运行后的稳定值
1、未开启优化:

 

 

2、开启优化后:

 感觉性能相差不大,可能这种基本的类库从远古时代2.0之后一般不怎么改动。

 



posted @ 2020-10-29 10:59  zhaogaojian  阅读(342)  评论(0编辑  收藏  举报