Logging

Logging always degrades performance. The penalty you pay depends to some extent on how logging is done. One possibility is using a final static variable to enable logging, as in the following code:

public final static boolean LOGGING = true;
...
if (LOGGING)
  System.out.println(...);

This code allows you to remove the logging code during compilation. If the LOGGING flag is set to false before compilation, the compiler eliminates the debugging code.[53] This approach works well when you need a lot of debugging code during development but don’t want to carry the code into your finished application. You can use a similar technique for when you do want logging capabilities during deployment, by compiling with logging features but setting the boolean at runtime.

An alternative technique is to use a logging object:

public class LogWriter {
  public static LogWriter TheLogger = sessionLogger( );
  ...
}
...
LogWriter.TheLogger.log(...)

This technique allows you to specify various LogWriter objects. Examples include a null log writer that has an empty log( ) method, a file log writer that logs to file, a sysout log writer logging to System.out, etc. Using this technique allows logging to be turned on after an application has started. It can even install a new type of log writer after deployment, which can be useful for some applications. However, be aware that any deployed logging capabilities should not do too much logging (or even decide whether to log too often), or performance will ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.