FULL PRODUCT VERSION :
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode)
ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [version 5.1.2600]
(and all others OSes...)
A DESCRIPTION OF THE PROBLEM :
nextBytes(byte[]) in java.util.Random could be faster, by avoiding divisions. The proposed implementation generates exactly the same sequence, but it generates 4 bytes per loop without using any division, with a minor unrolling of the generation loop which also simplifies the loop condition.
REPRODUCIBILITY :
This bug can be reproduced always.
CUSTOMER SUBMITTED WORKAROUND :
Change java.util.Random implemenation to use:
public void nextBytes(final byte[] bytes) {
int i = 0, n;
final int length;
n = (length = bytes.length) >> 2;
while (--n >= 0) {
final int rnd;
bytes[i] = (byte)(rnd = nextInt());
bytes[i + 1] = (byte)(rnd >> 8);
bytes[i + 2] = (byte)(rnd >> 16);
bytes[i + 3] = (byte)(rnd >> 24);
i += 4;
}
if ((n = length & 3) > 0) {
final int rnd;
bytes[i] = (byte)(rnd = nextInt());
if (n > 1) {
bytes[i + 1] = (byte)(rnd >> 8);
if (n > 2)
bytes[i + 2] = (byte)(rnd >> 16);
}
}
}
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode)
ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [version 5.1.2600]
(and all others OSes...)
A DESCRIPTION OF THE PROBLEM :
nextBytes(byte[]) in java.util.Random could be faster, by avoiding divisions. The proposed implementation generates exactly the same sequence, but it generates 4 bytes per loop without using any division, with a minor unrolling of the generation loop which also simplifies the loop condition.
REPRODUCIBILITY :
This bug can be reproduced always.
CUSTOMER SUBMITTED WORKAROUND :
Change java.util.Random implemenation to use:
public void nextBytes(final byte[] bytes) {
int i = 0, n;
final int length;
n = (length = bytes.length) >> 2;
while (--n >= 0) {
final int rnd;
bytes[i] = (byte)(rnd = nextInt());
bytes[i + 1] = (byte)(rnd >> 8);
bytes[i + 2] = (byte)(rnd >> 16);
bytes[i + 3] = (byte)(rnd >> 24);
i += 4;
}
if ((n = length & 3) > 0) {
final int rnd;
bytes[i] = (byte)(rnd = nextInt());
if (n > 1) {
bytes[i + 1] = (byte)(rnd >> 8);
if (n > 2)
bytes[i + 2] = (byte)(rnd >> 16);
}
}
}