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。
时间: 2024-11-08 21:28:41