【发布时间】:2009-11-18 13:26:29
【问题描述】:
我们使用以下方法来写出文本文件:
public void WriteFile(string filePath, string contents)
{
if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); }
if (contents == null) { throw new ArgumentNullException("contents"); }
if (File.Exists(filePath))
{
throw new InvalidOperationException(string.Format("The file '{0}' already exists", filePath));
}
StreamWriter sw = File.CreateText(filePath); // slow
sw.Write(contents);
sw.Close(); // slow
}
我们多次调用这个函数,所以性能是关键。注释slow 的两行代码是我们的应用程序花费大部分时间的地方。
参数contents 平均包含大约 10 KB 的文本。
.NET 或使用 Win32 API 的其他方法是否已知具有明显更好的性能?
我们已经尝试了以下方法:
TextWriter tw = new StreamWriter(filePath);
tw.Write(contents);
tw.Close();
但发现性能与我们最初的方法相似。
编辑
根据我们也尝试过的建议:
File.WriteAllText(filePath, contents);
但是,这种方法的性能与上面列出的其他方法相似。
【问题讨论】:
-
您尚未指定此写入的速度有多慢。说你的程序大部分时间都花在了那里,如果它以硬件允许的速度写那 10k 段文本,那并没有任何意义。
-
“慢”有多慢?请记住,大多数使用硬盘的工作比使用内存要慢得多......如果我们只是在写入期间谈论 3-5 毫秒的延迟,我不确定有很多事情要做...
-
@ApoY2K:我假设 Richard E 的意思是他正在编写许多不同的文件。如果他一遍又一遍地写相同的文件,你有一个很好的观点:-)
-
@scraimer, @ApoY2k:我正在写出许多不同的文件,已更新标题以反映这一点。
标签: .net performance file winapi file-io