tags:

views:

109

answers:

4

Would you expect better performance from A) or B) below if log level in the log4net config is set to Info level? Will _log.Debug on its own execute more code and take longer?

A)

if(_log.IsDebugEnabled)
  _log.Debug("some message");

B)

_log.Debug("some message");
+6  A: 

In this case, I'd use B.

However, if constructing the log message (the argument to log.Debug) may take a while - involving significant string concatenation, for example - then I would go for A. It will end up performing the same test twice in the "yes, log it" case, but it won't need to construct the log message in the "no, don't log it" case.

Jon Skeet
+1  A: 

Even though the first option is slightly more performant I would't worry so much.

However if you do something like this:

_log.Debug(String.Format("{0} {1} {2}...", param1, param2, param3));

then there is a strong case for checking _log.IsDebugEnabled before.

mgamer
+2  A: 

I would choose option B unless the log message itself takes a long time to construct. The performance gain for the usual case is negligible or doesn't even exist. Internally, log4net does the same check so you won't change anything by doing it yourself.

But as I said, option A may be a good idea in a situation like this:

if (_log.IsDebugEnabled())
{
    var message = createComplicatedLogMessageThatTakesALotOfTime();
    _log.Debug(message);
}

For all other cases, it just adds three more lines for every message you log which just isn't worth the effort.

Ronald Wildenberg
+2  A: 

Previous analysis revealed that Log4Net's IsXXXEnabled implementation isn't the fastest as it is calling several other methods. NLog's version does a volatile read, so it's much faster, but really, if your bottleneck lies in IsXXXEnabled you are already doing low-latency stuff and might end-up cooking your own dedicated logging.

Florian Doyon