Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better,using console.writeline() many times or saving the output on a stringbuilder and calling console.writeline once?

Tags:

c#

Which one is faster? Which one uses less memory?

Console.WriteLine("string1")
Console.WriteLine("string2")
Console.WriteLine("string3")
Console.WriteLine("stringNth")

or

StringBuilder output = new StringBuilder();
output.AppendLine("string1");
output.AppendLine("string2");
output.AppendLine("string3");
output.AppendLine("stringNth");
Console.WriteLine(output);

thanks,

like image 841
Newbie Avatar asked Apr 23 '09 23:04

Newbie


1 Answers

The first.

The console class is going to buffer this to the standard output stream.

With the second option, you're trying to create your own buffer, then buffer that again.

Take it to an extreme - do this 10,000,000 times. Your StringBuilder would eventually eat up all of your memory, where the Console would just be spitting out output.

like image 156
Reed Copsey Avatar answered Oct 26 '22 19:10

Reed Copsey