Problems with System.Random

Yesterday I ran a profiling tool (CLR Profiler) to see how Little Racers does with heap memory allocation, and found something strange: The log showed that class System.Random allocated around 88Mbytes of RAM during the whole execution.

The reason of this is the way the particle system works: Each particle stores only a seed to generate its random values, and a new Random is generated with that seed each time it needs to be updated (that is, on every frame). So, if we’re showing 50 particles on a frame, we’re calling new Random(seed) 50 times.

With System.Random, there was no possible workaround since it doesn’t have a method available to set the seed without recreating everything. Also, it seems to do some hard work on creation, maybe allocating the N next random numbers, I don’t know.

Anyway, I found a nice replacement called FastRandom: This class has the same interface that System.Random, so they can be easily interchanged. Also, it has a method to set the seed without having to recreate the class.

Anyway, I found a bug in the provided code, related with the methods Next(int) and Next(int,int) , it seems to store a double with the minimum value of an int and then multiply it by the desired range. It didn’t work for me, so I just replaced it with a modulus. Maybe it’s a little slower, but it works perfectly.

Tags: