1

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 ??

Archiac Coder
  • 156
  • 2
  • 13
  • 1
    I think it's better to use String.format("ServerSocketTimeOut = %s ReadTimeOut = %s", serversocketTimeout, sleepDelay). About the performance, you could test this by running a profiler for both versions although I don't see any point in doing so. The difference would be marginal. Download and use VisualVM. – Wesley De Keirsmaeker Feb 21 '20 at 19:23
  • Yes absolutely! I just wanted to tweak it and know will "+" operation in print behave the same as String concatenation? – Archiac Coder Feb 21 '20 at 19:25
  • 5
    Since this is all in a single line, the JVM will probably optimize version 1 into something like version 2 anyway. – azurefrog Feb 21 '20 at 19:27
  • The performance difference is essentially irrelevant, because the compiler will convert the first to something closely resembling the second. Go for the one which is most readable (that is, version 1). – Andy Turner Feb 21 '20 at 19:50

1 Answers1

2

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);

Matteo
  • 487
  • 4
  • 12