Is the string ctor the fastest way to convert an IEnumerable to string

后端 未结 2 1360
长情又很酷
长情又很酷 2020-12-10 05:34

Edited for the release of .Net Core 2.1

Repeating the test for the release of .Net Core 2.1, I get results like this

1000000 iter

2条回答
  •  孤街浪徒
    2020-12-10 05:44

    It's worth noting that these results, whilst true for the case of IEnumerable from a purists point of view, are not always thus. For example if you were to actually have a char array even if you are passed it as an IEnumerable it is faster to call the string constructor.

    The results:

    Sending String as IEnumerable 
    10000 iterations of "new string" took 157ms. 
    10000 iterations of "sb inline" took 150ms. 
    10000 iterations of "string.Concat" took 237ms.
    ======================================== 
    Sending char[] as IEnumerable 
    10000 iterations of "new string" took 10ms.
    10000 iterations of "sb inline" took 168ms.
    10000 iterations of "string.Concat" took 273ms.
    

    The Code:

    static void Main(string[] args)
    {
        TestCreation(10000, 1000);
        Console.ReadLine();
    }
    
    private static void TestCreation(int iterations, int length)
    {
        char[] chars = GetChars(length).ToArray();
        string str = new string(chars);
        Console.WriteLine("Sending String as IEnumerable");
        TestCreateMethod(str, iterations);
        Console.WriteLine("===========================================================");
        Console.WriteLine("Sending char[] as IEnumerable");
        TestCreateMethod(chars, iterations);
        Console.ReadKey();
    }
    
    private static void TestCreateMethod(IEnumerable testData, int iterations)
    {
        TestFunc(chars => new string(chars.ToArray()), testData, iterations, "new string");
        TestFunc(chars =>
        {
            var sb = new StringBuilder();
            foreach (var c in chars)
            {
                sb.Append(c);
            }
            return sb.ToString();
        }, testData, iterations, "sb inline");
        TestFunc(string.Concat, testData, iterations, "string.Concat");
    }
    

提交回复
热议问题