Reputation: 2886
Consider following statement and log level is set to ERROR. Logging API being used is log4j. How many strings will be created given above information?
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL query [" + sql + "]");
}
Other question is
if (logger.isDebugEnabled()) {
StringBuilder sBuilder = new StringBuilder("Executing SQL query [");
sBuilder.append(sql);
sBuilder.append("]");
logger.debug(sBuilder.toString());
}
How many string will be created in above case ?
My question is will compiler create strings even if logger is not enabled for debug ?
Upvotes: 1
Views: 145
Reputation: 328810
If you have quotes in your source code, then the compiler will put the string constant in the pool, no matter how complicated the code is. The compiler doesn't make many assumptions except when it can clearly see that code is unreachable (like if(false)
).
You may want to have a look at slf4j with logback which allows you to write
log.debug("Executing SQL query [{}]", sql);
Note that at runtime, it will still create a StringBuilder
and build the result from the pattern and arguments but slf4j will do the if
for you. That will keep your code clean and fast without a lot of effort.
You might want to look at project Lombok and their @Log annotation to make it even easier and more compact.
Upvotes: 2
Reputation: 122026
logger.debug("Executing SQL query [" + sql + "]");
Two strings
"Executing SQL query ["
"]"
created at compile time.
And then, in Runtime,
"Executing SQL query [" + sql + "]"
(+) operator JVM
returns new StringBuilder(string...).toString() which creates a new String instance in heap memory.
Append operation will happen with StringBuilder.toString
,If debug enable.
Upvotes: 2