"Premature Parameter Construction."(转载)

Be Careful of Premature Parameter Construction

Sometimes it is good to remember that arguments to a method are evaluated first before the method itself is called. Many moons ago, we concentrated our efforts on improving the performance of our application. However, several profiling and refactoring runs later, we found out that a HUGE chunk of this performance problem was caused by simple but numerous string concatenations and heavy toString() method calls.

It turned out that an old (but unfortunately huge) part of our app was sprinkled with method calls like this:

logger.debug("parameters: " + parameters.toString());

These thousands of string concatenations still happened although we had turned disabled the DEBUG logging level, because the string concatenation (and the call to parameters.toString()) happened before the debug() method is even called! This "unwanted parameter construction" is mentioned very clearly in log4j's FAQ and javadoc, but... people do forget.

In fact, I wrote this entry because several days ago, in a hurry, I wrote a line like the one above, which was really, really embarrassing because I was the one who cleaned up the old code and wrote an email to the whole team to be careful not to fall into this, er, pitfall again. Sigh.

Anyway, for cases like this, it is better for performance--albeit it may look less clean and redundant at first sight--to guard statements like the one above in a big if:

if(logger.isDebugEnabled()) {
    // logging statements here ...
    logger.debug("parameters: " + parameters);

Or in case of Logging API:

if(logger.isLoggable(Level.FINER)) {
    // logging statements here ...
    logger.finer("parameters: " + parameters);

There are cases in which it is faster to do a logger.debug() directly, when logging a string literal with DEBUG enabled:
logger.debug("Processing whatever...");

Because the checking for the effective logging level happens just once instead of twice. But this is irrelevant since it only happens in DEBUG mode anyway.


©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
钱包余额 0