David Silva David Silva - 3 months ago 11
C# Question

For loop advancing too quickly without generating random strings properly

So I coded a quick program to test how much difference it would make (in terms of processing speed) to check a boolean inside a foreach statement compared to checking it in a conditional statement outside of the loop. To test this I made a function generate random strings and add them to a list, but the for loop that generates the strings seems to advance too quickly without generating different strings in ever repetition. To fix this I added a

Thread.Sleep(15)
(15 milliseconds seems to be the minimum required to generate a different string in every repetition).

My question is this: is it possible to fix this issue without a
Thread.Sleep(15)
? Waiting 15 milliseconds between every repetition makes it so that the program takes a way bigger amount of time to run, which makes it highly unpractical for it's purpose (if I want to get statistically relevant data I'd have to run it around 10 thousand times for each option (the "good" and the "bad" way)). Here's the for loop in question:

for (int i = 0; i < 1000; i++) {

var stringChars = new char[8];
var random = new Random();

for (int n = 0; n < stringChars.Length; n++)
{
stringChars[n] = chars[random.Next(chars.Length)];
}

var finalString = new String(stringChars);
data.Add(finalString);
Thread.Sleep(15);
}

Answer

The problem you are getting is that you are recreating the Random class each time you iterate the loop.

The reason this is a problem is because the default seed for the Random class is the current system timestamp, which on repeated iterations could well be the same value.

Creating the Random outside of the for loop will ensure that a pseduo-random sequence is generated as you would expect.

Try this:

var random = new Random();

for (int i = 0; i < 1000; i++) {
    var stringChars = new char[8];

    for (int n = 0; n < stringChars.Length; n++)
    {
        stringChars[n] = chars[random.Next(chars.Length)];
    }

    var finalString = new String(stringChars);
    data.Add(finalString);
}
Comments