Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Console.WriteLine cause a performance penalty even when the console is not visible? (C#)

I have a console application with lots of WriteLine() functions, this application should also run as a "service" (a scheduled task, the user is not logged in when it runs).

In this case, there is no actual cmd window to show. Will Console.WriteLine() still cause a noticeable performance penalty in such a case?

like image 205
user1889878 Avatar asked Sep 20 '15 10:09

user1889878


People also ask

Does console WriteLine affect performance?

Yes, executing Console. WriteLine takes a measureable amount of time. Removing the Console. WriteLine call or changing it to a buffered background thread writing the data would really speed up the application.

Does console WriteLine slow down?

Console. WriteLine() ) is a sequential blocking call and under load that blocking is enough to seriously slow down request processing.

What does console WriteLine do in C#?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

How do I stop the console from disappearing in C#?

The first solution is to run the application without debugging by using Ctrl+F5 instead of just F5. The console window will remain open when the program has finished.


2 Answers

Yes it will cause performance penalty even when the console is not visible

my experiment was running this piece of code with the console visible and again with the console hidden and measure the performance

first run Console Visible 24683 Millisecond
second run Console Visible 23363 Millisecond

first run Console Hidden 167 Millisecond
second run Console Hidden 162 Millisecond

    static void Main(string[] args)
    {
        WriteMilionLines();
    }

    static void WriteMilionLines()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        for (int i = 0; i < 1000000; i++)
        {
           Console.WriteLine(i);
        }
        sw.Stop();

        string message = "ElapsedMilliseconds" + sw.ElapsedMilliseconds;
        File.WriteAllText(@"c:\log.txt", message);
    }

By commenting Console.WriteLine(i); line it will take Zero millisec

like image 185
George Botros Avatar answered Oct 02 '22 10:10

George Botros


No, it won't be noticeable. Unless your application does 99% Console.WriteLine() and barely anything else, the difference will be negligible.

If you still worry about performance, you could wrap Console-Calls into a method that you have control over and measure the total time your application went through and even introduce a switch (bool variable) to control its calls.

like image 37
CSharpie Avatar answered Oct 02 '22 12:10

CSharpie