When I first wrote this blog my intention was to introduce you to a class
ThreadLocalRandom which is new in Java 7 to generate random numbers. I have analyzed the performance of
ThreadLocalRandom in a series of micro-benchmarks to find out how it performs in a single threaded environment.
The results were relatively surprising: although the code is very similar,
ThreadLocalRandom is twice as fast as
Math.random()! The results drew my interest and I decided to investigate this a little further. I have documented my anlysis process. It is an examplary introduction into analysis steps, technologies and some of the JVM diagnostic tools required to understand differences in the performance of small code segments. Some experience with the described toolset and technologies will enable you to write faster Java code for your specific Hotspot target environment.
OK, that’s enough talk, let’s get started! My machine is an ordinary Intel 386 32-bit dual core running Windows XP.
Math.random() works on a static singleton instance of
ThreadLocalRandom -> current() -> nextDouble()works on a thread local instance of
ThreadLocalRandom which is a subclass of
ThreadLocal introduces the overhead of variable look up on each call to the
current()-method. Considering what I’ve just said, then it’s really a little surprising that it’s twice as fast as
Math.random() in a single thread, isn’t it? I didn’t expect such a significant difference.