I am working on a project in which I need to generate 8 random numbers. I am having an issue with the random number part being very time consuming for some reason. What I mean by 8 random numbers is I need a string that is 8 characters long consisting of the numbers 0-9. Example 01234567 or 23716253 etc.
I tried looping 8 times generating a random number with Random.Next(0, 9) and just turning them to a string and concatenating them to the final string. I also tried generating a random number using Random.Next(0, 99999999) and just converting the number to a string and padding it to 8 with 0's.
It seems like both are pretty slow and I need to come up with a faster way. I dont mind making calls to other languages or somthing either if it will help performance.
Here is some extra info to add. I dont think im going to find anything super efficient. I have to generate this number about 50000 times. When I ran a test with 47000 it took 8:39 seconds. This is only like .011 seconds each time but it was just slowing thins down because im also working with a has table. I also called hashtable.ContainsKey() all 47000 times and it only took a total of 58 seconds. It just is such a big difference.
Here is the code I origanally used. Convert.ToString(rg.Next(0, 99999999)).PadLeft(8, '0');
Here is some code to try to figure this out. Here are the times that I get Contains Value: 00:00:00.4287102 Contains Key: 00:01:12.2539062 Generate Key: 00:08:24.2832039 Add: 00:00:00
TimeSpan containsValue = new TimeSpan(); TimeSpan containsKey = new TimeSpan(); TimeSpan generateCode = new TimeSpan(); TimeSpan addCode = new TimeSpan(); StreamReader sr = new StreamReader(txtDictionaryFile.Text); string curWord = sr.ReadLine().ToUpper(); int i = 1; DateTime start; DateTime end; while (!sr.EndOfStream) { start = DateTime.Now; bool exists = mCodeBook.ContainsValue(curWord); end = DateTime.Now; containsValue += end - start; if (!exists) { string newCode; bool kExists; do { start = DateTime.Now; Random rnd = new Random(); StringBuilder builder = new StringBuilder(8); byte[] b = new byte[8]; rnd.NextBytes(b); for (int i = 0; i < 8; i++) { builder.Append((char)((b[i] % 10) + 48)); } newCode = builder.ToString(); end = DateTime.Now; generateCode += end - start; start = DateTime.Now; kExists = mCodeBook.ContainsKey(newCode); end = DateTime.Now; containsKey += end - start; } while (kExists); start = DateTime.Now; mCodeBook.Add(newCode, curWord); end = DateTime.Now; addCode += start - end; } i++; curWord = sr.ReadLine().ToUpper(); }