C#のstring接合操作の効率を比較し、stringBuilder、Format、および「+」.

2544 ワード

結果:
1、Format速度が一番遅い
2、「+」はFormatより5%-8%速い
3、stringBuilderは「+」より10%、つまり「Format」より15%速い
テスト手順は次のとおりです.
このうち3サイクルに分けて、毎回の前後にタイムスタンプを印刷します.
            int i = 0;
            var fs = File.Create(@"E://txt .txt");
            var sw = new StreamWriter(fs);

            string strTime = System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString() ;
            sw.Write("+ :" + strTime);
            sw.WriteLine();

            for (i = 0; i < 21885621; i++)
            {
                string sss = i.ToString() + " " + (i * 3).ToString() + " " + (i * i).ToString() + " " + (i + 1).ToString();
            }

            strTime = "
" + System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString() + "
"; sw.Write(strTime); sw.WriteLine(); strTime = System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString() + "
"; sw.Write("Format :" + strTime); sw.WriteLine(); for (i = 0; i < 21885621; i++) { string sss = string.Format("{0} {1} {2} {3}", i, i * 3, i * i, i + 1); } strTime = "
" + System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString() + "
"; sw.Write(strTime); sw.WriteLine(); strTime = System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString() + "
"; sw.Write("strBuilder :" + strTime ); sw.WriteLine(); StringBuilder strBuil = new StringBuilder(); for (i = 0; i < 21885621; i++) { // strBuil.Clear(); strBuil.Length = 0; strBuil.Append((i * 1000).ToString()).Append(" ").Append((i * 3).ToString()).Append( " ").Append((i * i).ToString()).Append(" ").Append((i + 1).ToString()); strBuil.ToString(); } strTime = "
" + System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString() + "
"; sw.Write(strTime); sw.WriteLine(); sw.Close(); fs.Close(); MessageBox.Show("OK");