我编写了以下代码来对 SLF4J(带有 Logback 绑定)的查找性能进行基准测试:
public final class LoggerTest {
private static final Logger staticLogger = LoggerFactory.getLogger(LoggerTest.class);
public static void main(final String[] args) {
warmUp(50000);
final int iterations = 1000000;
final long t1 = staticExecutionTime(iterations);
System.out.printf("Static time : %d%n", t1);
final long t2 = nontStaticExecutionTime(iterations);
System.out.printf("Non Static time : %d%n", t2);
}
private static void warmUp(final int iterations) {
executeStatic(iterations);
executeNonStatic(iterations);
}
private static long staticExecutionTime(final int iterations) {
final long s1 = System.nanoTime();
executeNonStatic(iterations);
final long e1 = System.nanoTime();
return e1 - s1;
}
private static void executeStatic(final int iterations) {
for (int i = 0; i < iterations; i++) {
staticLogger.trace("Do nothing!");
staticLogger.debug("Do nothing!");
}
}
private static long nontStaticExecutionTime(final int iterations) {
final long s2 = System.nanoTime();
executeNonStatic(iterations);
final long e2 = System.nanoTime();
return e2 - s2;
}
private static void executeNonStatic(final int iterations) {
for (int i = 0; i < iterations; i++) {
final Logger localLogger = LoggerFactory.getLogger(LoggerTest.class);
localLogger.trace("Do nothing!");
localLogger.debug("Do nothing!");
}
}
}
正如您在一个场景中看到的那样,我使用了一个在类加载期间初始化的静态记录器,而在另一种场景中,我每次都查找记录器。
我原以为使用静态记录器会更快,但是这两种情况几乎都花费了相同的时间,而且令人惊讶的是,非静态情况通常会快一点。
任何机构都可以描述这一点吗?