I am developing an application that intensively use randomly generated values.
I have two options:
The constraints are: I want to mantain the application to practically produce unique outputs.
What is the pros and cons between a single global Random object versus a set of local Random objects?
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.
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").
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