Pros and cons between one global Random object and a set of local random objects

Scenario

I am developing an application that makes heavy use of randomly generated values.

I have two options:

  • I create a single global random object that will be used throughout the application. All methods that need random values ​​have a parameter of type Random, to which I pass a global random object.
  • I do not create a global random object, but each method locally declares its random object.

Limitations: I want the application to practically produce unique output.

Question

What are the advantages and disadvantages of one global Random object compared to a set of local random objects?

+4
source share
2 answers

The problem with one Random is that you can pass it (directly or indirectly via asynchronous code / callbacks) to multiple threads. And since Random not thread safe, you will need to trust this code for synchronization. If you cannot trust the code, write a wrapper around Random that synchronizes for you, or can use an instance of [ThreadStatic] / ThreadLocal<T> .

Note also that random is not exactly the same as unique ...

However, if you declare it in a method, then any hard loop practically guarantees the same value for each iteration of the loop - for example,

 foreach(var foo in foos) foo.SomeMethod(); 

if SomeMethod starts a Random , you will most likely see duplicate values.

+5
source

In addition to what Mark said:

The advantage of a global random number generator is that you only need to sow once. This can be useful if you want reproducible results (for debugging, you can save the used seed and run the application later with the same seeds, if you do not think that the results are based on an error instead of β€œunlikely random numbers,”).

+4
source

Source: https://habr.com/ru/post/1335953/


All Articles