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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With