C#按行读取文本或字符串到数组效率测试:StreamReader ReadLine与Split函数对比

1. 读取文本文件测试:测试文件“X2009.csv”,3538行

耗时:4618ms

            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                string a = File.ReadAllText("X2009.csv", Encoding.Default);
                string[] arr = new string[3538];
                arr = a.Split(new char[] { '\r', '\n' });
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadLine();

耗时:2082ms

            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                string[] arr = new string[3538];
                int j = 0;
                using (StreamReader sr = new StreamReader("X2009.csv"))
                {
                    while (!sr.EndOfStream)
                    {
                        arr[j++] = sr.ReadLine();  // 额外作用,忽略最后一个回车换行符
                    }
                }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadLine();

 

2. 读取字符串测试:

耗时:8369ms

            string a = "0123456789\r\n0123456789\r\n0123456789\r\n0123456789\r\n0123456789\r\n" +
                "0123456789\r\n0123456789\r\n0123456789\r\n0123456789\r\n0123456789\r\n";
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                string[] arr = new string[10];
                arr = a.Split(new char[] { '\r', '\n' });
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadLine();

耗时:5501ms

                int j = 0;
                using (StringReader sr = new StringReader(a))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        arr[j++] = line;
                    }
                }

 

结论:

1. StreamReader ReadLine耗时约为Split函数的1/2

2. 对少量字符串Split函数性能足够,对含有大量字符串的文本文件适合使用StreamReader ReadLine函数

 

posted @ 2017-12-11 22:48  X2009  阅读(3806)  评论(0编辑  收藏  举报