0

Upon wrapping logging into a separate class, we experienced an increase in performance which we cant quite explain.

If anyone could perhaps comment to help us make sense of this?

Here is the main thread:

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());
    }
}
}

}

the logging wrapper class:

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);
}
}

Upon Thread.start() we get the following kind of output:

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

.....

Why is the wrapper out-performing the straight call? And this despite the added overhead of retrieving the caller-class name?

Arpit
  • 6,212
  • 8
  • 38
  • 69

1 Answers1

0

I would strongly reccommend reading up on micro benchmarks. This is a really interesting subject and I found this question useful as a starting point:

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

Essentially this is not a valid measure of performance as there are a whole heap of other things to take into consideration mainly around compiler optimisation

Community
  • 1
  • 1
cowls
  • 24,013
  • 8
  • 48
  • 78