lundi 28 août 2017

Multiple instantiations of Random() in tight loop

After reading Random Number Between 2 Double Numbers and MSDN: Random Class (System), I still do not understand why instantiating Random outside of a tight loop can avoid generating identical numbers.

MSDN says:

Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

I tested it and if a new Random is instantiated in the loop, I get identical results, and if I instantiated outside the loop or as a static variable, I get different random result. Why?

If Random uses a time-dependent seed value, either of the above would probably be speedily processed instantly with any modern processor, and should give me both identical results. And if not, even if I instantiate the Random outside of the loop, I still pull the value off the object in each loop and that loop should run fast enough that I would still get identical results.

Would someone help explain the concept more clearly?




Aucun commentaire:

Enregistrer un commentaire