Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

java - Inefficient use of string concatenation

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() + "]
");

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}]
", file.getName());

What's the different between these two ways of concatenation, I never used the latter though.

Cheers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...