我开始做如下事情:
using (TextWriter textWriter = new StreamWriter(filePath, append))
{
foreach (MyClassA myClassA in myClassAs)
{
textWriter.WriteLine(myIO.GetCharArray(myClassA));
if (myClassA.MyClassBs != null)
myClassA.MyClassBs.ToList()
.ForEach(myClassB =>
textWriter.WriteLine(myIO.GetCharArray((myClassB)));
if (myClassA.MyClassCs != null)
myClassA.MyClassCs.ToList()
.ForEach(myClassC =>
textWriter.WriteLine(myIO.GetCharArray(myClassC)));
}
}
这似乎很慢(35,000 行约 35 秒)。
然后我尝试按照这里的示例创建一个缓冲区,使用以下代码,但它没有给我任何帮助。我仍然看到大约 35 秒的时间。我如何实现缓冲区有错误吗?
using (TextWriter textWriter = new StreamWriter(filePath, append))
{
char[] newLineChars = Environment.NewLine.ToCharArray();
//Chunk through 10 lines at a time.
int bufferSize = 500 * (RECORD_SIZE + newLineChars.Count());
char[] buffer = new char[bufferSize];
int recordLineSize = RECORD_SIZE + newLineChars.Count();
int bufferIndex = 0;
foreach (MyClassA myClassA in myClassAs)
{
IEnumerable<IMyClass> myClasses =
new List<IMyClass> { myClassA }
.Union(myClassA.MyClassBs)
.Union(myClassA.MyClassCs);
foreach (IMyClass myClass in myClasses)
{
Array.Copy(myIO.GetCharArray(myClass).Concat(newLineChars).ToArray(),
0, buffer, bufferIndex, recordLineSize);
bufferIndex += recordLineSize;
if (bufferIndex >= bufferSize)
{
textWriter.Write(buffer);
bufferIndex = 0;
}
}
}
if (bufferIndex > 0)
textWriter.Write(buffer);
}
有没有更好的方法来实现这一点?