9

哪个更好或更正确?从类中创建一个对象StreamWriter并在方法中频繁使用它并最终处置它会更好吗?或者最好使用一个对象StringBuilder然后创建一个对象StreamWriter并立即处理它?

1)

var Write = new StreamWriter(string.Format("{0}{1}{2}", Environment.CurrentDirectory, Path.DirectorySeparatorChar, "Dummy.txt"));
for (int i = 0; i < 100; i++)
{
    //Do something include calculation 
    Write.WriteLine(something);
}
Write.Flush();
Write.Dispose();

2)

var Str = new StringBuilder();
for (int i = 0; i <     100; i++)
{
    //Do something include calculation 
    Str.AppendLine(something);
}
var Write = new StreamWriter(string.Format("{0}{1}{2}", Environment.CurrentDirectory, Path.DirectorySeparatorChar, "Dummy.txt"));
Write.Write(Str);
Write.Flush();
Write.Dispose();
4

2 回答 2

10

第一个可能使用更多的 IO 操作,但更少的内存。第二个需要缓冲内存中的所有内容。这可能是也可能不是问题。

更大的问题是您没有使用using语句或try/ finally,而您正在使用string.Format.

我会建议:

// Note the more conventional variable names, too...
string file = Path.Combine(Environment.CurrentDirectory, "Dummy.txt");
using (var writer = File.CreateText(file))
{
    for (int i = 0; i < 100; i++)
    {
        writer.WriteLine(...);
    }
}

此外,如果您正在编写的内容自然地表示为 LINQ 查询(或任何其他IEnumerable<string>),您可以使用File.WriteAllLines

var query = ...; // Something returning an IEnumerable<string>
var file = Path.Combine(Environment.CurrentDirectory, "Dummy.txt");
File.WriteAllLines(file, query);
于 2013-08-01T08:13:35.337 回答
4

It really depends on the context of your application. For example, if you have other programs listening to what comes out of that stream, and they can deal with the data a token at a time, then it's obviously preferable to go with the first approach.

That said, if you're just writing things out to a text file for storage, it will probably be worth going for the second option. I think the second option would probably run quite quickly, given that StringBuilder is pretty quick, and you're only performing one write operation, as opposed to the first option, where you're continually creating a new object for each write.

于 2013-08-01T08:13:09.020 回答