In PHP there is a function called mt_rand using the Mersenne Twister random number generator. I want to use the same function in Java, so I have found a class called MersenneTwisterFast. However, before I proceeded to use in my application, I would like to check "assert" their very attractive:
MersenneTwisterFast is not a subclass of java.util.Random. It has the same public methods as Random does, however, and it is algorithmically identical to MersenneTwister. MersenneTwisterFast has hard-code inlined all of its methods directly, and made all of them final (well, the ones of consequence anyway). Further, these methods are not synchronized, so the same MersenneTwisterFast instance cannot be shared by multiple threads. But all this helps MersenneTwisterFast achieve well over twice the speed of MersenneTwister. java.util.Random is about 1/3 slower than MersenneTwisterFast.
According to their "assertion", if I do not misunderstand, MersenneTwisterFast is 2 times faster than MersenneTwister and 3 times faster than Random. So, I tried on two methods: nextFloat() and nextInt() with 1 million calls.
This is the JMH code I use:
And this is the result:
As far as I understand, with the benchmark mode (AverageTime) that I choose, the lower the value of the score will bring the better performance and vice versa.
I tried to compare the source code of both MersenneTwisterFast and Random, but this is quite difficult because the source code on classpath.org and the source on OpenJDK is different. But anyway, really wondering why MersenneTwisterFast is 50 times slower than Random in this benchmark?
