问题
I usually generate random stuff in the following manner:
Random random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < 100; i++)
{
Console.WriteLine(random.Next(0, 100));
}
I was wondering whether there is a difference if I put the Random instantiation within the loop:
for (int i = 0; i < 100; i++)
{
Random random = new Random(DateTime.Now.Millisecond);
Console.WriteLine(random.Next(0, 100));
}
Which is more random or they are the same?
回答1:
The first (i.e. outside the loop) is more efficient AND more random since the second creates lots of Random
instances in very short time which will lead to several instances having the same seed (i.e. same Millisecond
) which in turn means generating the same random numbers over and over again.
From MSDN
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated.
回答2:
Outside of the loop, based on the samples in this documentation:
http://msdn.microsoft.com/en-us/library/system.random.aspx
回答3:
The first is more random, the second one may end up writing the same value a lot of times (as many as there are iterations in the same millisecond).
"Random" is not truly random, it uses an algorithm to calculate the next value from the previous one. The starting value (the 'seed') is just the first value in the sequence. So the same starting value results in the same sequence.
回答4:
You should reuse the Random variable. In your second example you'll often get the same result.
回答5:
The later is producing more random number. According to MSDN the value that you providing (Millisecond) is used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used.
So, Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers.
If your application requires different random number sequences, invoke this constructor repeatedly with different seed values.
More...
回答6:
i would suggest you to use first one beacuase your both immplementations are more less same but the second one could creates colliosions (same keys).
回答7:
Second way can create the same ouputs.
来源:https://stackoverflow.com/questions/7992399/instantiating-random-in-or-out-of-the-loop