Log4J意外性能提升

时间:2013-01-02 08:50:53

标签: performance log4j

在将日志记录包装到一个单独的类中时,我们遇到了性能提升,我们无法解释。

如果有人可以发表评论以帮助我们理解这一点?

以下是主要内容:

package myapp;

import myapp.logging.Log;

import org.apache.log4j.Logger;

public class ApplicationMain extends Thread {
private static Logger LOG = Logger.getLogger(ApplicationMain.class); 

@Override 
public void run() {
for (int i = 0; i < 50; i++) {
    try {
    Thread.sleep(500);

    //traditional plain log4j
    long startTime = System.nanoTime();
    LOG.info("Hello World Log4j");
    long endTime = System.nanoTime();
    System.out.println(endTime - startTime);

    //logging in wrapper
    long startTime2 = System.nanoTime();
    Log.Info("Hello World Log4J from within wrapper");
    long endTime2 = System.nanoTime();
    System.out.println(endTime2 - startTime2);

    } catch (InterruptedException ex) {
    Log.Info(ex.getMessage());
    }
}
}

}

日志记录包装类:

package myapp.logging;

import org.apache.log4j.Logger;

public class Log {


private static Logger LOG;

public static synchronized void Info(String LogMessage) {

Throwable throwable = new Throwable();
StackTraceElement[] stackTraceElements = throwable.getStackTrace();
LOG = Logger.getLogger(stackTraceElements[1].getClassName());
LOG.info(LogMessage);
}
}

Thread.start()后,我们得到以下类型的输出:

2013-01-02 10:42:25,359 INFO   [ApplicationMain] Hello World Log4j

191478

2013-01-02 10:42:25,359 INFO   [ApplicationMain] Hello World Log4J from within wrapper 

163852

2013-01-02 10:42:25,859 INFO   [ApplicationMain] Hello World Log4j 

166165

2013-01-02 10:42:25,859 INFO   [ApplicationMain] Hello World Log4J from within wrapper 

85361

2013-01-02 10:42:26,359 INFO   [ApplicationMain] Hello World Log4j 

188694

2013-01-02 10:42:26,359 INFO   [ApplicationMain] Hello World Log4J from within wrapper

82709

.....

为什么包装器执行直接呼叫?这虽然增加了检索调用者类名称的开销吗?

1 个答案:

答案 0 :(得分:0)

我强烈建议阅读微观基准。这是一个非常有趣的主题,我发现这个问题很有用:

How do I write a correct micro-benchmark in Java?

基本上这不是一个有效的性能衡量标准,因为主要围绕编译器优化需要考虑其他一大堆其他事项