stringbuilderの実行効率をテストする例

1881 ワード

 
  
// StringBuilder
        public static void Fun2()
        {
            #region string

            string str = " !";

            // , 。
            Stopwatch stopw = new Stopwatch();

            // 。
            stopw.Start();

            for (int i = 0; i < 100000; i++)
            {
                str += "Test";
            }

            // 。
            stopw.Stop();

            Console.WriteLine("string :" + stopw.ElapsedMilliseconds.ToString() + " ");

            #endregion

            #region StringBuilder

            StringBuilder sbuild = new StringBuilder(" !");

            stopw.Reset();
            stopw.Start();

            for (int i = 0; i < 100000; i++)
            {
                sbuild.Append("Test");
            }

            // 。
            stopw.Stop();

            Console.WriteLine("StringBuilder :" + stopw.ElapsedMilliseconds.ToString() + " ");

            #endregion

            #region String

            String str2 = " !";
            stopw.Reset();
            stopw.Start();

            for (int i = 0; i < 10000; i++)
            {
                str2 += "Test";
            }

            stopw.Stop();
            Console.WriteLine("String :" + stopw.ElapsedMilliseconds.ToString() + " ");


            // : StringBuilder
            #endregion
        }