O'Reilly Forums: Why Using A Random In A Creator Code? - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Why Using A Random In A Creator Code?

#1 User is offline   Silmarilion 

  • New Member
  • Pip
  • Group: Members
  • Posts: 2
  • Joined: 18-July 12

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?
0

#2 User is offline   Sikta_26785 

  • Active Member
  • PipPipPip
  • Group: Members
  • Posts: 68
  • Joined: 18-May 11

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.

Quote

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.

0

#3 User is offline   Silmarilion 

  • New Member
  • Pip
  • Group: Members
  • Posts: 2
  • Joined: 18-July 12

Posted 24 July 2012 - 04:51 AM

Thank you. Now I understood it just fine.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users