Log4j中的字符串连接性能 [英] String concatenation performance in Log4j

查看:50
本文介绍了Log4j中的字符串连接性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常听到人们说这是避免String Concatenation并在登录时改用{}的最佳实践之一.

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

我正在查看Log4j代码,以了解他们如何处理此问题,并认为他们正在做类似的事情.

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

这是format()方法的摘要,该方法采用模式和参数并返回要记录的消息.

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.

推荐答案

在日志记录系统中格式化字符串的好处是,日志记录系统可以决定是否必须进行字符串连接.

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

让我们以这些行为例:

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

只要此记录器的级别为debug或更低,性能就没有区别,但是,如果日志级别高于debug,则第二行根本不会执行串联操作.

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.

这篇关于Log4j中的字符串连接性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆