Most efficent way of joining strings

前端 未结 11 1734
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 05:51

I need to concatenate a lot of strings alltogether and put a comma between any of them. I have a list of strings

\"123123123213\"
\"1232113213213\"
\"1232131         


        
11条回答
  •  迷失自我
    2021-01-18 06:46

    According to the following test I've made, Join is 3x faster faster on large arrays:

    The Text.txt file contains the value "aaaaaaaaaaaaaaaaaaa" on 38400 lines:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Diagnostics;
    
    namespace ConsoleApplication1
    {
      class Program
      {
        static void Main(string[] args)
        {
          var strings = File.ReadAllLines("Text.txt");
    
          Stopwatch sw;
    
          StringBuilder sb = new StringBuilder();
    
          sw = Stopwatch.StartNew();
          for (int i = 0; i < strings.Length; i++)
          {
            sb.AppendLine(strings[i]);
          }
          sw.Stop();
          TimeSpan sbTime = sw.Elapsed;
    
          sw = Stopwatch.StartNew();
         var output = string.Join(",", strings);
         sw.Stop();
    
         TimeSpan joinTime = sw.Elapsed;   
    
        }
      }
    }
    

    Output:

    00:00:00.0098754
    00:00:00.0032922
    

提交回复
热议问题