Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and cons between a single global Random object versus a set of local Random objects

Tags:

c#

random

Scenario

I am developing an application that intensively use randomly generated values.

I have two options:

  1. I create a single global Random object to be shared throughout the application. All methods, that need random values, have a param of Random type to which I pass the global Random object.
  2. I don't create a global Random object but each method declares its Random object locally.

The constraints are: I want to mantain the application to practically produce unique outputs.

Question

What is the pros and cons between a single global Random object versus a set of local Random objects?

like image 634
xport Avatar asked Jan 21 '23 17:01

xport


2 Answers

The issue with a single Random is that you might be passing it (directly, or indirectly via async code / callbacks) to multiple threads. And since Random isn't thread-safe you would need to trust that code to synchronize. If you can't trust the code, write a wrapper around the Random that does the synchronization for you, or maybe use a [ThreadStatic] / ThreadLocal<T> instance.

Note also that random isn't quite the same thing as unique...

However, if you declare it in a method - then any tight loop is virtually guaranteed to generate the same value for each loop iteration - i.e.

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

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

like image 199
Marc Gravell Avatar answered Jan 30 '23 12:01

Marc Gravell


In addition to what Marc said:

The advantage of a global Random Number Generator is that you need to seed only once. This can be helpful if you want to get reproducible results (for debugging you can store the used seed and run the app later on with the same seeds if you don't believe the results are based on a bug instead of "unlikely random numbers").

like image 35
Philipp Avatar answered Jan 30 '23 13:01

Philipp