class Program { const int dataArraySize = 200; const int streamBufferSize = 2000; const int numberOfLoops = 10000; static int totalSize = 0; static void Main(string[] args) { StringBuilder sbFS = new StringBuilder(); StringBuilder sbBS = new StringBuilder(); FileStream fs = new FileStream(@"E:\1.txt", FileMode.Open, FileAccess.Read); BufferedStream bs = new BufferedStream(fs, streamBufferSize); byte[] by = new byte[dataArraySize]; int temp = 0; try { //FileStream Read DateTime startFS = DateTime.Now; while ((temp = fs.Read(by, 0, by.Length)) > 0) { totalSize += temp; //sbFS.Append(Encoding.GetEncoding("gb2312").GetString(by)); } double endFS = (DateTime.Now - startFS).TotalMilliseconds; Console.WriteLine("FileStream Read TotalBit : {0}", totalSize); Console.WriteLine("FileStream Read Time : {0}", endFS.ToString("F5")); //Reset temp = 0; totalSize = 0; Array.Clear(by, 0, by.Length); fs.Seek(0, SeekOrigin.Begin); //BufferedStream DateTime startBS = DateTime.Now; while ((temp = bs.Read(by, 0, by.Length)) > 0) { totalSize += temp; //sbBS.Append(Encoding.GetEncoding("gb2312").GetString(by)); } double endBS = (DateTime.Now - startBS).TotalMilliseconds; Console.WriteLine("BufferedStream Read TotalBit : {0}", totalSize); Console.WriteLine("BufferedStream Read Time : {0}", endBS.ToString("F5")); } finally { bs.Close(); bs.Dispose(); fs.Close(); fs.Dispose(); } Console.ReadLine(); } }
本地准备了一个13M的txt文本.用FileStream直接Read.
和BufferedStream的Read进行对比
每次对比结果:
FileStream Read TotalBit : 13664376
FileStream Read Time : 31.25000
BufferedStream Read TotalBit : 13664376
BufferedStream Read Time : 31.25000
=============================================
FileStream Read TotalBit : 13664376
FileStream Read Time : 15.62500
BufferedStream Read TotalBit : 13664376
BufferedStream Read Time : 31.25000
=============================================
FileStream Read TotalBit : 13664376
FileStream Read Time : 31.25000
BufferedStream Read TotalBit : 13664376
BufferedStream Read Time : 15.62500
=============================================
几次对比结果都是这样!
为什么用了BufferedStream没有对效率提高多少呢?而且有时反而还比直接用FileStream读慢呢?