Streamwriter vs StringBuilder

Which one works better or more correctly? Is it better to create an object from the StreamWriter class and often use it in a method and finally dispose of it? or is it better to use an object from StringBuilder and then create an object from StreamWriter and immediately delete it?

one)

 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(); 
+7
c #
source share
2 answers

The first potentially uses more I / O, but less memory. The second is to buffer everything in memory. This may or may not be a problem.

What else is the problem, you are not using the using or try / finally try , but 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(...); } } 

Also, if what you write naturally expresses itself as a LINQ query (or any other IEnumerable<string> ), you can simply use File.WriteAllLines :

 var query = ...; // Something returning an IEnumerable<string> var file = Path.Combine(Environment.CurrentDirectory, "Dummy.txt"); File.WriteAllLines(file, query); 
+9
source share

It really depends on the context of your application. For example, if you have other programs that listen to what comes out of this stream, and they can process data per token at a time, then obviously the first approach is preferable.

However, if you are just writing things to a text file for storage, it is probably worth going to the second option. I think the second option is likely to work pretty fast, given that StringBuilder pretty fast and you only perform one write operation, unlike the first option, where you constantly create a new object for each record.

+3
source share

All Articles