测试stringbuilder运行效率示例

 更新时间:2020年6月25日 11:38  点击:1439

复制代码 代码如下:

//测试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
        }

[!--infotagslink--]

相关文章