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() + "]
");
srcLogger.getLogger().log(Level.INFO, "UploadBean.doUpload completado [{0}]
", 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…