StringBuilder和Stopwatch使用初步

来源:互联网 发布:上瘾网络剧下载种子 编辑:程序博客网 时间:2024/05/17 01:38

string在进行运算时(如赋值、拼接等)会产生一个新的实例,而StringBuilder则不会。
所以在大量字符串拼接或频繁对某一个字符串进行操作时最好使用StringBuilder,而非string。

string类型在进行重复的拼接赋值操作的时候,之所以速度慢,效率低,是因为它在内存的堆中不停的开辟空间,而StringBuilder之所以速度快,效率高,是因为在整个的拼接、赋值操作中,它只是操作的一块内存,并没有再单独的开辟新空间(省略了开辟空间的时间)。


若要使用Stopwatch这个类,需要先添加命名空间引用:

using System.Diagnostics; //可以通过右键添加或者快捷键:Alt+Shift+F10

Stopwatch sw=new Stopwatch(); //这个类一般记录程序运行的时间
sw.Start();
        /*
        //add code
        */

sw.Stop();

Console.WriteLine(sw.Elapsed);


效果对比:

使用string时:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;namespace StringBuilderandStopWatch{    class Program    {        static void Main(string[] args)        {            string str = "";            Stopwatch sw = new Stopwatch();//这个类一般用来记录程序运行的时间            sw.Start();            for (int i = 0; i < 100000; i++)            {                str += "1";            }            sw.Stop();            Console.WriteLine(sw.Elapsed);            Console.ReadKey();        }    }}
耗时:


使用StringBuilder时:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;namespace StringBuilderandStopWatch{    class Program    {        static void Main(string[] args)        {            StringBuilder sb = new StringBuilder();            Stopwatch sw = new Stopwatch();//这个类一般用来记录程序运行的时间            sw.Start();            for (int i = 0; i < 100000; i++)            {             <span style="color:#FF0000;"><strong>   sb.Append("1");</strong></span>            }            sw.Stop();            Console.WriteLine(sw.Elapsed);            Console.ReadKey();        }    }}
耗时:


对比发现,两者相差竟达2835倍!



0 0