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. 讀取字符串測試:spa

耗時:8369mspwa

            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();

耗時:5501mscode

                int j = 0;
                using (StringReader sr = new StringReader(a))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        arr[j++] = line;
                    }
                }

 

結論:blog

1. StreamReader ReadLine耗時約爲Split函數的1/2字符串

2. 對少許字符串Split函數性能足夠,對含有大量字符串的文本文件適合使用StreamReader ReadLine函數string

相關文章
相關標籤/搜索