Here i will add logger.isDebugEnabled() conditional statement for logger.debug().
But sometime there are many logger.debug() in loop. For example:
Logger log = Logger.getLogger(Test.class);
for(int i = 0; i < 1000; i++) {
...
log.debug("aaaaa");
...
for(int j = 0; i < 100; j++) {
...
log.debug("bbbb");
}
}
If i add it directly, as follows:
for(int i = 0; i < 1000; i++) {
...
if(log.isDebugEnabled()) {
log.debug("aaaaa");
}
...
for(int j = 0; i < 100; j++) {
...
if(log.isDebugEnabled()) {
log.debug("bbbb");
}
}
}
So, in the loop, it will if() many times. How could i use less if(logger.isDebugEnabled())?
Does anyone have some idea ?
thanks.
Consider this code:
The cost of the
iftest could be as small as 2 instructions, depending how the JIT compiler’s register allocation pans out. This is most likely insignificant, unless you are doing ridiculous amounts of logging.However, if the performance hit of those 2 to 4 instructions really matters, then you could consider:
removing the call to
logentirely,making it conditional on a compile time constant (so that the optimizer can prune the code), or
hoisting the test out of the loop; e.g. restructuring the code as follows:
However, IMO, the cure is worse than the disease.
@Vineet’s point is important too. In practice, the expensive part of something like this:
is that the String concatenation expression is evaluated irrespective of the actual logging level. There are other ways to avoid this overhead apart from an
iftest … though they will be more expensive than aniftest on a cached flag.