按行讀取文本或字符串到數組效率測試:StreamReader與Split函數對比
阿新 • • 發佈:2017-12-12
sed ade csv tel style null con nco str
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函數對比