Thursday, February 24, 2011

Cleaner CDK Code #9: using the LoggingTool

A trick I used from Miguel Howard (of Jmol fame) is to not concatenate String until really needed. String concatenation will allocate new Strings, and thus burden the garbage collector (yeah, you lucky Fortran users who think twice before allocating memory :). Some time ago, he suggested this trick for the logger. I think in Jmol, but the CDK inherited that idea.

Don't concatenate Strings when calling the LoggingTool
Logging in the CDK can be turned off, and in production use, I often do. Therefore, we can make it speed up by concatenating debug message String only when debugging is turned on. The CDK LoggingTool can take care of this, so you should pass the Strings are individual parameters to the logger call. Instead of:

    logger.debug("the current atom is " + atom);

you should write:

    logger.debug("the current atom is ", atom);

And this works for any arbitrary number of Strings and objects, because the logging tool debug method has this signature: public void debug(Object object, Object... objects). So, you can also just do:

    logger.debug("The ", i, "th object is connected to the ", j, "th");

Actually, looking at the debug() method's signature, I am not sure why we still have the first Object separately... mmm.

1 comment:

  1. Oh, the signatures with (Object object) are there because the base case of (Object... object) has zero arguments instead of one argument. This prevents the user from logging a blank message.

    Having said that, a user can //still// log a blank message with the empty string (""). From a design perspective, I don't know that going out of one's way to stop this behaviour is worth it :P