Most efficient way to concatenate strings?

后端 未结 17 1586
野趣味
野趣味 2020-11-22 03:04

What\'s the most efficient way to concatenate strings?

17条回答
  •  野的像风
    2020-11-22 03:50

    Try this 2 pieces of code and you will find the solution.

     static void Main(string[] args)
        {
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < 10000000; i++)
            {
                s.Append( i.ToString());
            }
            Console.Write("End");
            Console.Read();
        }
    

    Vs

    static void Main(string[] args)
        {
            string s = "";
            for (int i = 0; i < 10000000; i++)
            {
                s += i.ToString();
            }
            Console.Write("End");
            Console.Read();
        }
    

    You will find that 1st code will end really quick and the memory will be in a good amount.

    The second code maybe the memory will be ok, but it will take longer... much longer. So if you have an application for a lot of users and you need speed, use the 1st. If you have an app for a short term one user app, maybe you can use both or the 2nd will be more "natural" for developers.

    Cheers.

提交回复
热议问题