I was creating a logger in my java-app (with NetBeans as IDE) when suddenly I saw a warning saying: "Inefficient use of string concatenation in logger".
My oringinal code is
srcLogger.getLogger().log(Level.INFO,"UploadBean.doUpload completado [" + file.getName() + "]\n");
but NetBeans suggested to convert it to a template (what a "template" means here?) giving this code:
srcLogger.getLogger().log(Level.INFO, "UploadBean.doUpload completado [{0}]\n", file.getName());
What's the different between these two ways of concatenation, I never used the latter though.
Cheers.
The message is not referring to the cost of the String concatenation in of itself. The other answers are absolutely right when they say that a StringBuilder will be used.
The main reason to use a Message Template is because the processing is only done when the logging level is being displayed!
Let us use these two examples:
srcLogger.getLogger().log(Level.INFO,"UploadBean.doUpload completado [" + file.getName() + "]\n");
srcLogger.getLogger().log(Level.INFO, "UploadBean.doUpload completado [{0}]\n", file.getName());
With debug level INFO on: Both have to get the filename from File, both have to update the string, generate a new one, display it.
With debug level INFO off: The second answer passes through the name of the File object (which is a simple query), the log() method checks the INFO level and returns immediately. No String
processing is performed at all!
Now imagine that instead of a simple file.getName()
we were logging a more complex object, one that itself needed a lot of string concatenation in the toString()
method. By logging those objects directly none of that processing is done at all. toString()
is never even called unless the debug level is being displayed.
So Message Template is not more efficient in the case where the logging is being displayed, but it is enormously more efficient (particularly in cases of non-trivial logging) when the logging is not being displayed. One of the goals of logging should be that if the logging is turned off it has the smallest possible impact on the performance of the system.
I'd ignore the warning (and switch if it off, if possible). The concatenation is not that inefficient, because modern compilers replace it with an efficient implementation based on StringBuilder
(you'll see it if you look at the classfile's bytecode).
The suggested replacement doesn't concatenate Strings but it requires some extra processing to parse the template and merge it with the parameters.
Netbeans, that's a bad advice.
This is true for Java 1.5+. Older versions of Java (may) create a lot of unused String
instances during concatenation..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With