FileReadTest.exe 1.txt
共有 294586 行,耗时: 00:00:00.8328959
共有 294587 行,耗时: 00:00:02.6531879
显然速度没有可比性,基本上不是一个数量级的。第一行是ReadLine,第二行是ReadToEnd再Split。
这次我又随机抽了一个小一点儿的约1M的文件来测试:
FileReadTest.exe 2.txt
共有 45885 行,耗时: 00:00:00.0759722
共有 45886 行,耗时: 00:00:00.1749030
速度仍然不具备可比性。
100K的文件:
FileReadTest.exe 3.txt
共有 831 行,耗时: 00:00:00.0008885
共有 832 行,耗时: 00:00:00.0019791
完败……
测试程序:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace FileReadTest
{
class Program
{
static Stopwatch watch = new Stopwatch();
static void Main( string[] args )
{
string filepath = Path.Combine( Path.GetDirectoryName( Process.GetCurrentProcess().MainModule.FileName ), args[0] );
using ( StreamReader reader = new StreamReader( filepath ) )
{
watch.Start();
int linecount = 0;
while ( reader.ReadLine() != null )
{
linecount++;
}
watch.Stop();
Console.WriteLine( "共有 {0} 行,耗时: {1}", linecount, watch.Elapsed );
}
GC.Collect();
using ( StreamReader reader = new StreamReader( filepath ) )
{
watch.Start();
int linecount = 0;
string s = reader.ReadToEnd();
linecount = s.Split( '\n' ).Length;
watch.Stop();
Console.WriteLine( "共有 {0} 行,耗时: {1}", linecount, watch.Elapsed );
}
}
}
}
