How to fill byte array with junk?

flyout picture flyout · Jun 6, 2010 · Viewed 21.5k times · Source

I am using this:

byte[] buffer = new byte[10240];

As I understand this initialize the buffer array of 10kb filled with 0s.

Whats the fastest way to fill this array (or initialize it) with junk data every time?

I need to use that array like >5000 times and fill it every time with different junk data, that's why I am looking for a fast method to do it. The array size will also have to change every time.

Answer

Joren picture Joren · Jun 6, 2010

Answering 'the fastest way' is impossible without describing what the properties of your junk data have to be. Why isn't all zeroes valid junk data?

That said, this is a fast way to fill your array with meaningless numbers.

Random r = new Random();
r.NextBytes(buffer);

You might also look at implementing your own Linear congruential generator if Random isn't fast enough for you. They're simple to implement and fast, but won't give high quality random numbers. (It's unclear to me if you need those or not.)