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:

WaaghMan March 11th, 2009 Development, XNA Programming

Avatar Ninja Box Art

MotorHEAT Box Art

Little Racers Box Art

Little Racers Box Art

  • Retro game of the week: Duke Nukem 1
    http://www.youtube.com/watch?v=c4a3_wazRPA
    2010/09/06 06:59
  • For those who didn't notice, our games Wool and MotorHEAT are finalists in 3 categories at the Hó Play International Videogame Festival!
    2010/09/02 08:27
  • Check out this nice review of MotorHEAT!
    http://fb.me/FdZoypY2
    2010/09/02 08:34
  • Our games Wool and MotorHEAT are nominees at the Hó Play International Festival!
    http://twtn.gs/bkr
    2010/08/31 09:01
  • Retro Game of the Week: Jumping Flash! by Exact and Ultra (PlayStation)
    http://www.youtube.com/watch?v=N2hukvZ0zBw
    2010/08/30 12:35
  • Retro Game of the Week: Transport Tycoon Deluxe
    http://www.youtube.com/watch?v=HluOjdtxmNU
    2010/08/23 06:05
  • Congratulations to @brenes, he's the lucky winner of the 1600MP code!
    2010/08/21 12:11
  • Check out Avatar Ninja, a highly rated Indie game for Xbox 360! - RT & Follow for a chance to win 1600MP!
    http://bit.ly/acaB7W
    2010/08/20 20:40
  • Check out Avatar Ninja, a highly rated Indie game for Xbox 360! RT & Follow for a chance to win 1600MP!
    http://bit.ly/acaB7W
    2010/08/20 13:04
  • Retro game of the week: Rise of the Triad, a First Person Shooter by Apogee
    http://www.youtube.com/watch?v=eMf4KzlbzI8
    2010/08/20 06:51