Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation performance in Log4j

I have often heard people saying that its one of the best practices to avoid String Concatenation and use {} instead while logging.

I was looking into the Log4j code to see how they have handled this and figured that they are doing something similar.

Here is a snippet of format() method which takes the pattern and arguments and returns the message to be logged.

/**
 * Formats arguments using SLF4J-like formatter.
 * @param pattern pattern, may be malformed.
 * @param arguments arguments.
 * @return Message string
 */
private static String format(final String pattern,
                             final Object[] arguments) {
    if (pattern != null) {
        String retval = "";
        int count = 0;
        int prev = 0;
        int pos = pattern.indexOf("{");
        while(pos >= 0) {
            if (pos == 0 || pattern.charAt(pos-1) != '\\') {
                retval += pattern.substring(prev, pos);
                if (pos + 1 < pattern.length() && pattern.charAt(pos+1) == '}') {
                    if(arguments != null && count < arguments.length) {
                        retval += arguments[count++];
                    } else {
                        retval += "{}";
                    }
                    prev = pos + 2;
                } else {
                    retval += "{";
                    prev = pos + 1;
                }
            } else {
                retval += pattern.substring(prev, pos - 1) + "{";
                prev = pos + 1;
            }
            pos = pattern.indexOf("{", prev);
        }
        return retval + pattern.substring(prev);
    }
    return null;
}

I'm not able to understand how this implementation is better than using concatenation. Any insights into this will be really helpful.

like image 853
user2004685 Avatar asked May 02 '18 22:05

user2004685


People also ask

What is the best way to concatenate strings in Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class. This shot will discuss how to perform string concatenation using both of these methods.

How do you solve format specifiers should be used instead of string concatenation?

Instead of concatenating the string with + (in "Error in x file :",+ e. getMessage() ), you can use String. format to build the string instead: Logger.


1 Answers

The benefit of format strings in logging systems is, that the logging system can decide if the string concatenation must happen or not.

Let's use these lines as example:

log.debug("Count: " + list.size());
log.debug("Count: {}", list.size());

As long as the level for this logger is debug or below, there is no difference in performance, but if the log level is higher than debug the second line won't perform the concatenation at all.

like image 60
larsgrefer Avatar answered Oct 11 '22 14:10

larsgrefer