A
A
AlenAfrikyan2021-10-02 18:41:09
C++ / C#
AlenAfrikyan, 2021-10-02 18:41:09

What is the difference and how to do it right?

What is the difference, and how to do it right: create an instance or directly call?

Random random = new Random();
int r = random.Next(1, 10);

int r1 = new Random().Next(1, 10);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
spaceatmoon, 2021-10-02
@AlenAfrikyan

For a single call, there is no difference. However, logically, calling the constructor slows down the program much more than just calling the Next function.

DateTime timeStart = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
    int random = new Random().Next(1, 10);
}
DateTime timeStop = DateTime.Now;
Console.WriteLine("new Random().Next(1, 10) - {0}", timeStop - timeStart);
//
timeStart = DateTime.Now;
Random random1 = new Random();
for (int i = 0; i < 10000; i++)
{
    int dig = random1.Next(1, 10);
}
timeStop = DateTime.Now;
Console.WriteLine("random.Next(1, 10) - {0}", timeStop - timeStart);

new Random().Next(1, 10) - 00:00:00.0209561
random.Next(1, 10) - 00:00:00.0001170

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question