C# the comparison between FileStream.Write() and StreamWriter.Write()

原文:C# the comparison between FileStream.Write() and StreamWriter.Write()

C# the comparison between FileStream.Write() and StreamWriter.Write()
 
C# the comparison between FileStream.Write() and StreamWriter.Write()
 static void FileStreamSDemo()
        {
            DateTime dtNow = DateTime.Now;
            DateTime dtEnd = dtNow.AddSeconds(60);
            using(FileStream fs=new FileStream("FileStream.txt",FileMode.Create))
            {
                while (DateTime.Now < dtEnd)
                {
                    string msg = $"Now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")},Guid is {Guid.NewGuid()}";
                    byte[] data = Encoding.UTF8.GetBytes(msg);
                    fs.Write(data, 0, data.Length);
                }
            }           
        }

        static void StreamWriterDemo()
        {
            DateTime dtNow = DateTime.Now;
            DateTime dtEnd = dtNow.AddSeconds(60);
            using(StreamWriter writer=new StreamWriter("StreamWriter.txt",true,Encoding.UTF8))
            {
                while(DateTime.Now<dtEnd)
                {
                    string msg = $"Now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")},Guid is {Guid.NewGuid()}";
                    writer.WriteLine(msg);
                }
            }
        }
C# the comparison between FileStream.Write() and StreamWriter.Write()

 


C# the comparison between FileStream.Write() and StreamWriter.Write()

 

In fact,during the identical time,the streamwriter generated much more data.

In my pc,StreamWriter.txt is 2.03 GB (2,187,534,336 bytes)

While FileStream.txt is 1.86 GB (1,998,835,712 bytes),

Based on the above fact and data,The streamwriter  has speed advantages.

C# the comparison between FileStream.Write() and StreamWriter.Write()

上一篇:MPC8313ERDB不新建pkg包,把文件放进Ramdisk


下一篇:C#缓存加载数据与读取