Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streamwriter vs StringBuilder

Tags:

c#

Which one does work better or is more correct? Is it better to create an object from StreamWriterclass 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();
like image 814
Mohammad Avatar asked Aug 01 '13 08:08

Mohammad


1 Answers

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);
like image 124
Jon Skeet Avatar answered Nov 15 '22 21:11

Jon Skeet