What is the preferred way to use the Random
class in Java ?
a) Create one object of Random
and use it many times
b) Create a new object of Random
each time a random value is needed
What are the drawbacks and beneftis ?
Technically, the guarantee made by the class is that a single instance will produce a pseudorandom stream of values. With your method (b), there's no explicit guarantee that the resulting stream of values would meet the same statistical definition of randomness. So if you care about true statistical randomness, (a) would be preferred.
I don't see much benefit to (b). I suppose it means you don't need to hold onto a reference to a single instance of Random, but doing that in a singleton class would be straightforward. Generally I would be wary of creating lots of new objects for performance reasons, but you could measure the impact and decide whether it was acceptable.
So between these options I would usually prefer (a).
I can see a third option, of using more than one long-lived instance. You might do that if you have multiple threads and you want each to use its own Random
object. (It's unclear to me from the javadoc what the implication are of having multiple threads calling a single object might be.)
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