I have a method in a class where I create a string like this:
private void log(HttpServletRequest request, HttpServletResponse response) {
String result = "Following request " + request.getRequestURI() + " yielded " + response.getStatus();
log.info(result);
}
My question is, result string is generated millions of times. Does it have impact on heap memory?
My current understanding is that each method has its own heap memory allocation. After method finishes executing, all local variables vanish from memory.
My other understanding is that Strings are stored in global heap memory, and they get cleaned up on next Garbage collection cycle.
Can someone please put some light on this I shall be thankful.
logthough (but I guess that soon releases the string, after logging it).+calls toStringBuilderusages (or even better since Java 9), so that part is good already. And you can not compute the string at compile time since the URI and response status change each time. The only thing you could optimize is to get rid of the temporary variableresult. Instead, create the string directly in thelog.info(...)call. But that is about it.