在实际开发中不少人在输出debug日志的时候会先判断一下日志框架是否允许debug如下
if(logger.isDebugEnabled()) {
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
}
会觉得性能会更好一些,那么这么做是否有必要呢?其实logger.debug方法内部本身就会进行一次判断,外面的if判断就显得多余,针对这个问题日志官网是结论是什么呢?
One possible way to avoid the cost of parameter construction is by surrounding the log statement with a test. Here is an example.
if(logger.isDebugEnabled()) {
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
}
This way you will not incur the cost of parameter construction if debugging is disabled for logger. On the other hand, if the logger is enabled for the DEBUG level, you will incur the cost of evaluating whether the logger is enabled or not, twice: once in debugEnabled and once in debug. In practice, this overhead is insignificant because evaluating a logger takes less than 1% of the time it takes to actually log a request.
实际上,这个开销是微乎其微的,因为在logger.debug内部判断是否需要输出日志花费的时间占输出整个日志的时间的1%都不到,外层加一个if(logger.isDebugEnabled()),在真的打开debug后反而会有两次判断,在关闭debug时也至少要进行一次if test,所以简单起见在打印日志时直接一行
logger.debug("Entry number: {}" ,String.valueOf(entry[i]));就够了。
所谓的性能影响完全是有些人想当然,自作多情

在Java开发中,对于logger.debug的日志输出,有人认为应该先判断日志级别以提高性能。然而,日志框架内部已包含判断机制,额外的if检查并不必要。官方建议表明,这种外部判断带来的性能提升微乎其微,而且在启用debug时可能导致两次判断。因此,直接使用logger.debug方法更简洁高效。所谓的性能影响通常是过度担忧。
3537





