字符串连接性能

本文通过对比不同字符串拼接方式(普通拼接、StringBuilder、List结合Join)在不同次数及字符串长度下的性能表现,展示了在C#中进行字符串操作时的最佳实践。
   class Program
   {
      private static readonly string STR = "0123456789";
      private static string longSTR = StringList(1024, STR);

      static void Main(string[] args)
      {
         Test(10000, STR);
         Test(10, longSTR);
      }

      public static void Test(int count, string str)
      {
         for (int i = 2; i <= 1024; i *= 2)
         {
            Time(string.Format("Nomal  Concat ({0})", i), count, () => Concat(i, str));
            Time(string.Format("StringBulider ({0})", i), count, () => StringBulider(i, str));
            Time(string.Format("String   List ({0})", i), count, () => StringList(i, str));
            Console.WriteLine();
         }
      }

      public static void Time(string name, int count, Func<string> function)
      {
         var watch = new Stopwatch();
         watch.Start();
         for (int i = 0; i < count; i++)
         {
            function();
         }
         watch.Stop();
         Console.WriteLine(name + watch.ElapsedTicks);
         watch.Reset();
      }

      public static string Concat(int count, string str)
      {
         var result = string.Empty;
         for (int i = 0; i < count; i++)
         {
            result += str + "|";
         }
         return result;
      }

      public static string StringBulider(int count, string str)
      {
         var result = new StringBuilder();
         for (int i = 0; i<count; i ++)
         {
            result.Append(str + "|");
         }
         return result.ToString();
      }

      public static string StringList(int count, string str)
      {
         var result = new List<string>();
         for (int i = 0; i < count; i++)
         {
            result.Add(str);
         }
         return string.Join("|", result);
      }
   }

  

转载于:https://www.cnblogs.com/xiao-hei/p/4920929.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值