We are using concatenated strings almost everywhere for logging purposes.
For eg: catch (Exception e) {
logger.error("setUserSession()" + e.getMessage());
}
But we doubt if these statements cause memory leaks because of string mutation. Some suggests to use String builder. But what I understood from discussions like StringBuilder vs String concatenation in toString() in Java is Java Compiler will convert string concatenations with the use of String builder.
To test this I have tried to decompile following java codes(using JD-GUI);
logger.error("string1" + "string2");
logger.error("setUserSession()" + e.getMessage());
And decompiler produced following code;
logger.error("string1string2");
logger.error("setUserSession()" + e.getMessage());
But I was expecting the String builder in second statement like ;
logger.error(new StringBuilder().append("setUserSession()").append(e.getMessage());
So I have 2 doubts here:
- Does string concatenation actually creates so much memory leaks?
- Or do I need to use String builder explicitly->append my strings to string builder->then delete string builder using string builder delete function?
- Java compiler converts simple string concatenations with String builder. (And we can use decompiler tools to check that?)