Generating Random Numbers Efficiently in Loops
The following code snippet demonstrates a common pitfall when generating random numbers within a loop:
<code class="language-csharp">// Inefficient random number generation public static int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); }</code>
Calling this function repeatedly in a tight loop, for example:
<code class="language-csharp">byte[] mac = new byte[6]; for (int x = 0; x < 6; x++) { mac[x] = (byte)RandomNumber(0, 255); }</code>
will often result in identical values within the mac
array. This is because Random
is re-initialized with the system clock in each iteration. If the loop executes quickly, the clock hasn't changed significantly, resulting in the same seed and thus the same sequence of "random" numbers.
The Solution: A Single, Shared Instance
The correct approach involves creating a single Random
instance and reusing it throughout the loop. Thread safety should also be considered for multi-threaded applications. Here's an improved version:
<code class="language-csharp">// Efficient and thread-safe random number generation private static readonly Random random = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock (syncLock) { return random.Next(min, max); } }</code>
By using a static readonly
instance, we ensure only one Random
object is created. The lock
statement protects against race conditions in multi-threaded scenarios, guaranteeing that only one thread accesses the random.Next()
method at a time. This maintains the integrity and randomness of the generated numbers.
The above is the detailed content of Why Do Repeated Calls to `Random.Next()` in a Tight Loop Produce Identical Numbers?. For more information, please follow other related articles on the PHP Chinese website!