Why Using A Random In A Creator Code?

  • Please log in to reply
2 replies to this topic

#1 Silmarilion


    New Member

  • Members
  • Pip
  • 2 posts

Posted 18 July 2012 - 10:05 AM

Well I was wondering. the book has a lot of examples using constructors like

public ClassIWant(Random random, int something...)

In which I need an instance to a Random Object. If I need a Random object to generate data. Wouldn't it be easier just to get it instantiated directly in the Creator without having to get an instance of this Random guy?
I mean, it's random isn't? I think it adds some unwanted complexity to the code doesn't?

#2 Sikta_26785


    Active Member

  • Members
  • PipPipPip
  • 68 posts

Posted 18 July 2012 - 05:14 PM

It's considered best practice to use one instance of the Random class to generate random numbers. You can find why here. I quoted the important part of this page.

By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. This problem can be avoided by creating a single Random object rather than multiple ones. To improve performance, create one Random object to generate many random numbers over time, instead of repeatedly creating a new Random objects to generate one random number.

#3 Silmarilion


    New Member

  • Members
  • Pip
  • 2 posts

Posted 24 July 2012 - 04:51 AM

Thank you. Now I understood it just fine.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users