Most efficent way of joining strings

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

    Test code:

    public static void Performance(Action fn)
    {
        var timer = new Stopwatch();
        timer.Start();
    
        for (var i = 0; i < 10000000; ++i)
        {
            fn();
        }
    
        timer.Stop();
    
        Console.WriteLine("{0} Time: {1}ms ({2})", fn.ToString(), timer.ElapsedMilliseconds, timer.ElapsedTicks);
    }
    
    static void Main(string[] args)
    {
        var stringList = new List() {
            "123123123213",
            "1232113213213",
            "123213123"
        };
    
        string outcome = String.Empty;
        Performance(() =>
        {
            outcome = string.Join(",", stringList);
        });
    
        Console.WriteLine(outcome);
    
        Performance(() =>
        {
            StringBuilder builder = new StringBuilder();
            stringList.ForEach
                (
                    val =>
                    {
                        builder.Append(val);
                        builder.Append(",");
                    }
                );
            outcome = builder.ToString();
            outcome = outcome.Substring(0, outcome.Length - 1);
        });
    
        Console.WriteLine(outcome);
    
        Console.ReadKey();
    
    }
    

    Result 1. String.Join - 2. StringBuilder + SubString. ####ms (ticks)

    result

    In this case String.Join is faster, but if you are ok with a trailing , then

    string builder

    StringBuilder is slightly faster (with a trailing ,).

提交回复
热议问题