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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM