我开始做以下事情:
@H_301_2@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秒).
然后我尝试按照示例here创建一个缓冲区,使用以下代码,但它没有获得任何东西.我仍然看到大约35秒的时间.我是如何实现缓冲区的?
@H_301_2@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(),buffer,bufferIndex,recordLineSize); bufferIndex += recordLineSize; if (bufferIndex >= bufferSize) { textWriter.Write(buffer); bufferIndex = 0; } } } if (bufferIndex > 0) textWriter.Write(buffer); }有没有更好的方法来实现这一目标?
解决方法
我把一个简单的片段扔到一起,我认为它更清洁;但是,再一次,我不太确定你想要完成什么.另外,我没有任何课程,所以我不能做任何类型的测试.
这个样本与你的基本相同;除了它使用一些通用方法,它在一个地方完成所有写作.
@H_301_2@string filePath = "MickeyMouse.txt"; bool append = false; List<MyClassA> myClassAs = new List<MyClassA> { new MyClassA() }; List<char[]> outputLines = new List<char[]>(); foreach (MyClassA myClassA in myClassAs) { outputLines.Add(myIO.GetCharArray(myClassA)); if (myClassA.MyClassBs != null) outputLines.AddRange(myClassA.MyClassBs.Select(myClassB => myIO.GetCharArray(myClassB))); if (myClassA.MyClassCs != null) outputLines.AddRange(myClassA.MyClassCs.Select(myClassC => myIO.GetCharArray(myClassC))); } var lines = outputLines.Select(line => string.Concat<char>(line)); if (append) File.AppendAllLines(filePath,lines); else File.WriteAllLines(filePath,lines);这是StringBuilder版本:
@H_301_2@string filePath = "MickeyMouse.txt"; bool append = false; List<MyClassA> myClassAs = new List<MyClassA> { new MyClassA() }; StringBuilder outputLines = new StringBuilder(); foreach (MyClassA myClassA in myClassAs) { outputLines.Append(myIO.GetCharArray(myClassA)); if (myClassA.MyClassBs != null) myClassA.MyClassBs.ForEach(myClassB=>outputLines.Append(myClassB)); if (myClassA.MyClassCs != null) myClassA.MyClassCs.ForEach(myClassC => outputLines.Append(myClassC)); } if (append) File.AppendAllText(filePath,outputLines.ToString()); else File.WriteAllText(filePath,outputLines.ToString());