Most efficent way of joining strings

前端 未结 11 1752
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    This adhoc implementation I tried with the StrignBuilder is faster than String.Join. More than that String.Join is a MEMORY HOG. I tried with 20000000 strings and String.Join always gives OutOfMemory, when my implementation finishes. On your machine It may be even on less strings if you have less than 8Gb of memory. Comment one of the implementations to test. This holds true unless you use a fixed string[] array. String.Join is good there.

       public static void Main(string[] Args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    
              List strings = new List() {};
            for (double d = 0; d < 8000000; d++) {
                strings.Add(d.ToString());
            }
    
            TimeSpan upTime;
            TimeSpan newupTime;
            using (var pc = new PerformanceCounter("System", "System Up Time"))
            {
                StringBuilder sb = new StringBuilder(strings.Count);
                int i;
    
                pc.NextValue();    //The first call returns 0, so call this twice
                upTime = TimeSpan.FromSeconds(pc.NextValue());
    
                for (i = 0; i < strings.Count - 1; i++)
                {
                    sb.Append(strings[i]);
                    sb.Append(",");
                }
                sb.Append(strings[i]);
    
                newupTime = TimeSpan.FromSeconds(pc.NextValue());
                sb = null;
                Console.WriteLine("SB " + (newupTime - upTime).TotalMilliseconds);
            }
    
            using (var pc = new PerformanceCounter("System", "System Up Time"))
            {
    
                pc.NextValue();
                upTime = TimeSpan.FromSeconds(pc.NextValue());
    
                string s = string.Join(",", strings);
    
                newupTime = TimeSpan.FromSeconds(pc.NextValue());
                Console.WriteLine("JOIN " + (newupTime - upTime).TotalMilliseconds);
            }
    
    
        }
    SB 406
    JOIN 484
    

提交回复
热议问题