Does "+" concatenation operation in java in System.out.print() consume memory?

Archiac Coder :

I am having a doubt regarding the usage of String and String Builder in Java. I am using Java 1.8

Version one :

System.out.println("ServerSocketTimeOut = " + serversocketTimeout + " ReadTimeOut = " + readTimeout  + " SleepDelay =" + sleepDelay);

Version Two:-

StringBuilder viewString= new StringBuilder("ServerSocketTimeOut = ");
viewString.append(serversocketTimeout).append(" ReadTimeOut = ")
                        .append(readTimeout).append("SleepDelay =").append(sleepDelay)

Shall I gain any performance in terms of memory as StringBuilder is mutable?

Version_1 vs Version_2 ??

Matteo :

In java 1.6+ probably the optimizer will make the performances of your two versions equal.

But keep in mind, in more complex concatenation you could have actually better performance with StringBuilder. (read for instance Java: String concat vs StringBuilder - optimised, so what should I do? )

If I was you I would consider too delegating to some logging framework with parameters, ( read for instance Built-in string formatting vs string concatenation as logging parameter )

Here a brief example of possible "version 3"

LOGGER.info("ServerSocketTimeOut = {} ReadTimeOut = {} SleepDelay = {}", serversocketTimeout, readTimeout, sleepDelay);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=419903&siteId=1