开发者

Fastest way to randomize a large amount of strings

开发者 https://www.devze.com 2023-03-22 14:35 出处:网络
I would like to declare (and randomize) about 500 strings. I believe I have two options here: 1: Create an array with a size of 500.

I would like to declare (and randomize) about 500 strings.

I believe I have two options here:

1: Create an array with a size of 500.

string[] x = new string[500];

for(int i = 0; i < 500; i++)
{
    x[i] = Randomize_thisString(); // Some routine 
}

2: Declare (and randomize) 500 different strings.

string string_one = Randomize_thisString();
string string_two = Randomize_thisString();
string string_n = Randomize_thisString(); 

...

Which o开发者_JAVA百科ne of these would be the faster method, and does anyone know of a third option here?

Thank you,

Evan


I will go with first choice, since this will just run once and it not takes much time.
An idea on how create a function to generate the random string I will uses System.IO.Path.GetRandomeFileName() The testing code:

System.IO.Path.GetRandomFileName();

Stopwatch watch = Stopwatch.StartNew();
string[] x = new string[500];

for (int i = 0; i < 500; i++)
{
    x[i] = System.IO.Path.GetRandomFileName();
}

watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);

result is 2.


What do you mean by

Declare (and randomize) 500 different strings.

string a1 = GenerateRandomString();
string a2 = GenerateRandomString();
string a3 = GenerateRandomString();
.
.
.
.
string a500 = GenerateRandomString();

If so maybe you should revise this lesson

BTW As in both cases program is executed line by line there shouldn't be difference in time required to generate strings


Just a thought. Not sure if you need all 500 strings upfront.

If you were using this in a loop to do some action, you could use yield to create string only when you need them.

 public IEnumerable<string> GetRandomString()
    {
      for(int i=0; i<500; i++)
       yield return RandomizeString();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消