I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java\'s Random class.>
I had some fun with your code and came up with this:
public class XORShiftRandom {
private long last;
private long inc;
public XORShiftRandom() {
this(System.currentTimeMillis());
}
public XORShiftRandom(long seed) {
this.last = seed | 1;
inc = seed;
}
public int nextInt(int max) {
last ^= (last << 21);
last ^= (last >>> 35);
last ^= (last << 4);
inc += 123456789123456789L;
int out = (int) ((last+inc) % max);
return (out < 0) ? -out : out;
}
}
I did a simple test and it is about Four times as fast as the java.util.Random
If you are intrested in how it works you can read this paper:
Disclamer:
The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.