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函数

 

转载于:https://www.cnblogs.com/x2009/p/8025441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值