Reputation: 799
I'm doing 100's of logarithmic and power calculations inside a Java program. The second time onwards the time it takes (Using System.nanotime()) is way faster than the first instance. Why? Does Java (I use JDK8) use any in-memory caching for Math calculations?
Upvotes: 1
Views: 207
Reputation: 100279
At the very first Math calculation the JVM need at least to load the Math
class from the hard drive into memory, verify it (scan for errors) and parse it to extract the methods, annotations, etc. It's much slower than calculating logarithm. Thus very first access to the class may be many times slower than the consequent accesses.
During the further iterations the JIT-compilation of your code can be triggered (so-called on-stack replacement) and your testing method will be compiled, thus you may have even more speed-up as calls to Math methods would simply be replaced with CPU instructions, reducing the overhead of passing the parameters to the native code as well as interpreter work on iteration. Also if your test is badly written and you don't use the results of the calculations, the JIT-compiler may remove the call to Math library at all.
Finally for such fast methods like Math.log
the nanotime may produce too imprecise results. Consider writing proper JMH benchmark.
Upvotes: 3