Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...