I am trying to generate large byte arrays of random bytes. Using the below code I can generate 10 million random bytes and place in a byte array in about 4 seconds. 2 seconds for the generation and 2 second to place on the array.
for (var i:Number = 0; i < reqLength; i++){
rnd = Math.random() * 255;
randomBytes.writeByte(rnd);
}
Does a faster way exist?
I am generating ints because I am creating a byte array of extended ASCII chars.
With a few tweaks I tuned it down from 4s to 0.5s.
var aBytes:ByteArray = new ByteArray;
// Set the final ByteArray length prior to filling it.
// It saves about 30% of elapsed time.
aBytes.length = 10000000;
// Write 2 500 000 x 4 byte unsigned ints instead of 10 000 000 x 1 bytes.
// You'll get 4 times less operations thus it is about 4 times faster.
for (var i:int = 0; i < 2500000; i++)
{
// Don't use local variable = less operations.
aBytes.writeUnsignedInt(Math.random() * uint.MAX_VALUE);
}
P.S. There's another funny option, works much faster, like 100ms:
var aRaster:BitmapData = new BitmapData(5000, 500, true, 0x000000);
var aBytes:ByteArray = new ByteArray;
aRaster.noise(256 * Math.random());
aRaster.copyPixelsToByteArray(aRaster.rect, aBytes);