基准测试看似简单,但是由于JVM会在运行时做优化,可能使得基准测试的结果失去意义。

比如JVM如果“看到”接口只有一种实现时,会对接口方法的调用做优化。 如果在后续运行中“看到”很多的接口实现时,则会抛弃掉之前的优化。 这会导致对第二个接口实现的benchmark结果变得不准确。 其它JVM优化手段还有dead-code elimination、constant folding等等。

所谓基准测试,意味着有baseline,有对比,JVM的优化会导致对比的某一方得到了“不公平的”优待,使得对比的结果失去了意义。

文章推荐使用jmh来做基准测试。

it was developed as part of the OpenJDK project

JMH is popular for writing microbenchmarks, that is, benchmarks that stress a very specific piece of code. …