"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.

原文连接:http://www.javaworld.com/weblogs/cprog/archives/000315.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值