Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

c# - What consumes less resources and is faster File.AppendText or File.WriteAllText storing first in StringBuilder?

I have to write thousands of dynamically generated lines to a text file. I have two choices, Which consumes less resources and is faster than the other?

A. Using StringBuilder and File.WriteAllText

StringBuilder sb = new StringBuilder();

foreach(Data dataItem in Datas)
{
    sb.AppendLine(
        String.Format(
            "{0}, {1}-{2}",
            dataItem.Property1,
            dataItem.Property2,
            dataItem.Property3));
}

File.WriteAllText("C:\example.txt", sb.ToString(), new UTF8Encoding(false)); 

B. Using File.AppendText

using(StreamWriter sw = File.AppendText("C:\example.txt"))
{
    foreach (Data dataItem in Datas)
    {
        sw.WriteLine(
            String.Format(
                "{0}, {1}-{2}",
                dataItem.Property1,
                dataItem.Property2,
                dataItem.Property3));
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your first version, which puts everything into a StringBuilder and then writes it, will consume the most memory. If the text is very large, you have the potential of running out of memory. It has the potential to be faster, but it could also be slower.

The second option will use much less memory (basically, just the StreamWriter buffer), and will perform very well. I would recommend this option. It performs well--possibly better than the first method--and doesn't have the same potential for running out of memory.

You can speed it quite a lot by increasing the size of the output buffer. Rather than

File.AppendText("filename")

Create the stream with:

const int BufferSize = 65536;  // 64 Kilobytes
StreamWriter sw = new StreamWriter("filename", true, Encoding.UTF8, BufferSize);

A buffer size of 64K gives much better performance than the default 4K buffer size. You can go larger, but I've found that larger than 64K gives minimal performance gains, and on some systems can actually decrease performance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...