String和StringBuilder的區別

CSF践行發表於2024-08-18
            //建立一個控制檯應用程式,在Mian()方法中編寫如下程式碼,驗證字串操作和可變字串操作的執行效率。
            string str = "";
            long longStartTime = DateTime.Now.Millisecond;
            for (int i = 0; i < 10000; i++)
            {
                str = str + i;
            }
            long longEndTime = DateTime.Now.Millisecond;
            long time = longEndTime - longStartTime;
            Console.WriteLine(time);

            StringBuilder str1 = new StringBuilder();
            longStartTime = DateTime.Now.Millisecond;
            for (int j = 0; j < 10000; j++)
            {
                str1.Append(j);
            }
            longEndTime = DateTime.Now.Millisecond;
            time = longEndTime - longStartTime;
            Console.WriteLine(time);

            Console.ReadLine();

相關文章