0

A C# .NET exe (4.6.1) outputs a lot of status by calling a method that does Console.Writeline. So much that it visibly slows down execution. First thought was to add a bool and/not do the Writeline within the called method based on the value. However, if the exe does 4000 Writelines that is 4000 checks, which seems excessive.

What is a good way to short-circuit the output? A way to do Console.SetOut to null somehow?

Thanks.

Snowy
  • 5,942
  • 19
  • 65
  • 119
  • 4
    I think a `bool` would be pretty light compared to calling `Console.Writeline` – cost Apr 23 '16 at 00:44
  • 1
    Surely you won't be outputting anything in your release build? Just add a compiler directive `#if DEBUG`. – Luke Joshua Park Apr 23 '16 at 00:48
  • A `bool` check would be much faster than any sort of access to `Console`. Have you actually profiled your app to see how much the `bool` comparison is actually costing? I'd suspect not, or you wouldn't have bothered to ask this question. The only optimization you might have is to not all the method that does the `WriteLine` at all - remove it completely unless you enable it for debugging or tracing purposes. – Ken White Apr 23 '16 at 00:48

2 Answers2

0

You could use delegates to solve this problem although I'm sure checking bools is probably significantly faster than Console.WriteLine().

Add a delegate to the class:

public delegate void Output(string message);

Then at the start of the application you can check your bool and assign which method to run depending on if you want to actually write or not.

bool logInformation = true;

if(logInformation)
{
    ProcessInformation((s) => { Console.WriteLine(s); });
}
else
{
    ProcessInformation((s) => { });
}

And finally add the delegate to your method signature for your processing method.

private void ProcessInformation(Output logger)
{
    // doing stuff, time to write
    logger("test");
}

You'll need to replace your Console.WriteLine calls with logger() but that will allow you to run things without worrying about checking a bool each time. That said I don't know if it's actually faster than checking a bool each time but probably easier to implement and maintain.

0

To answer your exact question:

Console.SetOut(TextWriter.Null);

But the System.Diagnostics TraceEvent call gives you much more granular control over what you are outputting. For example, in prod you could output only "Error" messages, while developing you can output your verbose logs. https://msdn.microsoft.com/en-us/library/system.diagnostics.tracesource.traceevent(v=vs.110).aspx

adotout
  • 1,170
  • 12
  • 17