[other] Why no code guard when logging? (1 Viewer)

erikture

MP Donator
  • Premium Supporter
  • March 26, 2008
    87
    5
    Home Country
    Sweden Sweden
    Hello!

    I have looked into the MediaPortal code and found that there are a lot of logging on different levels, debug, info, error and so on.
    Logging is always good, but I have one question about the way it is implemented in MediaPortal.

    There are no build in code guard function in the Log class.
    If you write for example Log.Debug("Some debug message");
    The string "Some debug message" will be constructed every time this debug method is called. If debug is not switched on then the string is thrown away, i e the string is constructed for no reason. Strings are always expensive to constuct.

    If you instead write something like this:

    if(Log.isDebugEnabled){
    Log.Debug("Some debug message");
    }

    It is even more expensive if you do something like this Log.Debug(string.Format("Some message: {0}",aString)); without code guared. Then the string.Format will execute for no reason as well.

    Where isDebugEnabled is a bool property, the string will only be created when needed.
    Calling a bool property does not take any time.
    In the logging library log4net there is methods like this.

    Just a thought that might improve performance.

    /Erik
     

    spiderwheels

    Portal Pro
    October 28, 2009
    101
    3
    Home Country
    United Kingdom United Kingdom
    String literals are not expensive to construct. There is no construction as they are already in there in the assembly.

    As you say, this:

    Log.Debug(string.Format("Some message: {0}",aString));

    is expensive as the string.Format is called regardless of the log level.

    In this instance the line should use the built in formatting methods of the Log class:

    Log.DebugFormat("Some message: {0}",aString);

    Now the parameters are passed to the DebugFormat method and formatting only takes place if Debug is enabled.
     

    Users who are viewing this thread

    Top Bottom