码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-12 00:15:09      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:测试   log   star   top   while   odi   strong   body   blog   

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

耗时:4618ms

            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                string a = File.ReadAllText("XX.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("XX.csv"))
                {
                    while (!sr.EndOfStream)
                    {
                        arr[j++] = sr.ReadLine();  // 额外作用,忽略最后一个回车换行符
                    }
                }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadLine();

 

2. 读取字符串测试:

耗时:8369ms

            string a = "0123456789\r\0123456789\r\0123456789\r\0123456789\r\n0123456789\r\n" +
                "0123456789\r\0123456789\r\0123456789\r\0123456789\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;
                    }
                }

 

结论:StreamReader耗时约为Split函数的1/2。

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

标签:测试   log   star   top   while   odi   strong   body   blog   

原文地址:http://www.cnblogs.com/x2009/p/8025441.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!