Which one does work better or is more correct?
Is it better to create an object from StreamWriter
class and use it frequently in a method and finally dispose it? or is it better to use an object from StringBuilder
then create an object from StreamWriter
and immediately dispose it?
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();
The first potentially uses more IO operations, but less memory. The second needs to buffer everything in memory. That may or may not be a problem.
What's more of a problem is that you're not using a using
statement or try
/finally
, and that you're using string.Format
.
I would suggest:
// 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(...);
}
}
Additionally, if what you're writing is naturally expressed as a LINQ query (or any other IEnumerable<string>
) you can just use File.WriteAllLines
:
var query = ...; // Something returning an IEnumerable<string>
var file = Path.Combine(Environment.CurrentDirectory, "Dummy.txt");
File.WriteAllLines(file, query);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With