我编写了以下代码来测试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!");
}
}
}
正如您在一个场景中所看到的,我使用了一个在类加载时间内初始化的静态记录器,而在另一个场景中,我每次都会查找记录器。
我期望使用静态记录器的速度更快,但两种情况几乎都花费相同的时间,并且令人惊讶的是非静态场景通常会更快。
任何人都可以形容这个吗?
答案 0 :(得分:1)
你的方法
private static long staticExecutionTime(final int iterations) {
final long s1 = System.nanoTime();
executeNonStatic(iterations);
final long e1 = System.nanoTime();
return e1 - s1;
}
正在执行错误的内部方法:p
应该拨打executeStatic(iterations);
而不是executeNonStatic(iterations);
纠正它,你会得到一个不同的图片:)