DCSIMG
Random.NextBytes Performance Issues - Dotmad (on .Net)

Dotmad (on .Net)

Just Another Web 5.0 Blog

Podcasts

Blogroll

Random.NextBytes Performance Issues

 בעיות ביצועים עם מחלקת Random

I have became aware recently to a performance problem with the Random class, specifically the Random.NextBytes method.
As it turns out this is an expansive operation:
Random Performance Statistics
The graph displays the number of milliseconds used to perform 10,000,000 operations.
The NextBytes method handle a byte array containing only 4 bytes.
This is linear - using an array of 4000 bytes will take 1000 times longer to complete the operation!

However, there may be a work-around using the BitConverter class.
Use BitConverter.GetBytes(Random.NextDouble()) to get a randomized array of 8 bytes.

Here are the results:
Using BitConverter

As you can see, generating an array of 8 bytes this way takes half the time of generating it using the NextBytes method.

תוכן התגובה

ekampf כתב/ה:

At first glance it seems to me like you're potentially hurting the uniformity here...

Given a random double in uniform distribution between 0 to 1 can you assume that each byte composing it is uniform for 0..255?

# March 4, 2008 10:14 PM

Adi כתב/ה:

From the few tests I ran it seems it is, but I can check it again.

# March 5, 2008 7:55 AM