这是对我之前的问题Log to memory 然后 write to file的引用,实际上是该问题的编辑部分,我在编辑部分询问如果我写入内存会比写入文件更快吗?我做了一个简单的测试,结果令人震惊!我想与社区分享。所以这是代码
private void Button1Click(object sender, EventArgs e)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
File.AppendAllText(@"D:\File1.txt", string.Format("{0}Start! : {1}", Environment.NewLine, DateTime.Now.ToString(CultureInfo.InvariantCulture)));
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 1000000; j++)
{
File.AppendAllText(@"D:\File1.txt", string.Format("{0}{1}:{2}", Environment.NewLine, i.ToString(CultureInfo.InvariantCulture), j.ToString(CultureInfo.InvariantCulture)));
}
}
File.AppendAllText(@"D:\File1.txt", string.Format("{0}Done!{1}", Environment.NewLine, DateTime.Now.ToString(CultureInfo.InvariantCulture)));
stopwatch.Stop();
File.AppendAllText(@"D:\File1.txt",
string.Format("{0}{1}:{2}",Environment.NewLine, stopwatch.Elapsed.ToString(), stopwatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture)));
MessageBox.Show("Done!");
}
private void Button2Click(object sender, EventArgs e)
{
var stopwatch = new Stopwatch();
using (var mem = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(mem))
{
stopwatch.Start();
{
binaryWriter.Write("start! : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 1000000; j++)
{
binaryWriter.Write(i.ToString(CultureInfo.InvariantCulture) + ":" + j.ToString(CultureInfo.InvariantCulture));
}
}
stopwatch.Stop();
binaryWriter.Write("Done! " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
binaryWriter.Write(stopwatch.Elapsed.ToString() + ":" + stopwatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture));
binaryWriter.Flush();
var file = new FileStream(@"D:\File2.txt", FileMode.Create);
mem.WriteTo(file);
}
}
}
MessageBox.Show("Done!");
}
因为代码应该很容易理解
Elapsed time in File1.txt = 00:50:24.5654918
Elapsed milliseconds in File1.txt = 3024565
Elapsed time in File2.txt = 00:00:04.7430152
Elapsed milliseconds in File2.txt = 4743
因此,正如您自己所见,大约有 50 分钟的差异!这可能是导致性能不佳的真正原因,如果您将所有内容直接记录到 IO 文件,而不使用内存流或任何用于记录的自定义工具,OTOH与 File.AppendAllText 的 50 分钟相比,使用 MemoryStream 只需要大约 4 和四分之一第二。(我仍然对为什么 Windows 资源管理器中显示的时间与 stopwatch.ShowElapasedTime 最后显示的文件中的时间不对应感到困惑,但尽管如此,即使我们看到 Windows 资源管理器时间,它仍然快了大约 45 分钟!)所以,这可能是一个非常有用的东西,我想分享它!