Sunday, May 1, 2011

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

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,

From stackoverflow
  • What value of "better" are you looking for? Speed? Memory use?

  • The best way to find out would be to time 10,000 iterations of each and see which is faster. I suspect that they will be almost identical in terms of performance.

  • 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.

  • Windows WriteConsole API writes strings line by line, so you don't really gain much by buffering output. The slowdown occurs on display output rather than consecutive API calls.

    Note that WriteConsole fails for buffers larger than 64KB according to this MSDN article.

    The fastest would be writing less. For instance if you're writing progress, write every 1000th iteration rather than each, you get the idea.

    And with StringBuilder approach if an exception is raised before you flush, you lose the buffered output, bad for debugging purposes.

0 comments:

Post a Comment