Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating Random in or out of the loop

Tags:

c#

random

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?

like image 957
Kiril Stanoev Avatar asked Aug 30 '25 18:08

Kiril Stanoev


1 Answers

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.

like image 115
Yahia Avatar answered Sep 02 '25 07:09

Yahia