How do you prevent flushing to the screen for Console.WriteLine()? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do you prevent flushing to the screen for Console.WriteLine()?

In visual studio (console application), this one runs extremely slow: for (int i = 0; i < 9999; i++) Console.WriteLine(i); I suppose that after each loop run the console gets flushed thus making it slow. How do I prevent this?

12th Jun 2022, 7:12 AM
Sea Carp
Sea Carp - avatar
2 Answers
+ 3
The standard doesn't specify that Console.WriteLine flushes the output https://docs.microsoft.com/en-us/dotnet/api/system.console.writeline This thread also suggests the same thing https://stackoverflow.com/questions/16791167/console-writeline-c-sharp-loses-stdout-when-logging So it's not the flushing that's causing your loop to run slow. Loops this big are slow by themselves. Why are you looping 9999 times anyways?
12th Jun 2022, 7:54 AM
XXX
XXX - avatar
+ 3
Most of the time in this code is spent on the console window having to scroll the screen. It would run faster if you use Write and separate the numbers with spaces to fit more information in horizontally rather than vertically. A small amount of extra time is spent in i/o overhead from so many calls to WriteLine. You could build a single string in the loop, and then make only one call to Write after the loop, though I'm not certain that this would be a significant speedup: string s = ""; for (int i = 0; i < 9999; i++) s += i.ToString() + '\n'; Console.Write(s);
12th Jun 2022, 8:39 AM
Brian
Brian - avatar