内存缓冲区和IO操作

时间:2012-06-22 21:00:44

标签: c# performance io

以下两个代码示例在性能方面是否相同?

代码示例1:

var count = 9999999999;

using(var sw = new StreamWriter())
{
   for(int i=0;i<count;i++)
   {
      var result = SomeRelativeLongOperation(i);
      sw.WriteLine(result);    
   }
}

代码示例2:

var count = 9999999999;
var resultCollection = new ....

using(var sw = new StreamWriter())
{
   for(int i=0;i<count;i++)
   {
      resultCollection.Add(SomeRelativeLongOperation(i));

      if(resultCollection.Count%100==0)
      {
         WriteBlock(sw,resultCollection);    
         resultCollection.Clear();
      }
   }
}

我知道Windows使用内存缓冲区进行IO操作。因此,当我调用StreamWriter.WriteLine方法时,它首先将数据存储在内存中,然后刷新到硬盘驱动器,对吧?

1 个答案:

答案 0 :(得分:0)

StreamWriter已经缓冲,因此添加额外的缓冲区只会降低效率。