使用 StringBuilder 组装字符串将使您的处理量增加 600 倍(因为它避免了每次附加到字符串时重复创建对象。
before 循环(初始化容量避免在 StringBuilder 中重新创建后备数组):
StringBuilder sb = new StringBuilder(1000000 * ReadLength);
在循环中:
sb.Append(all.Substring(randomPos, ReadLength) + Environment.NewLine);
循环后:
readString = sb.ToString();
使用 char 数组而不是字符串来提取值可以再提高 30%,因为您可以避免在调用 Substring() 时创建对象:
循环前:
char[] chars = all.ToCharArray();
在循环中:
sb.Append(chars, randomPos, ReadLength);
sb.AppendLine();
编辑(不使用 StringBuilder 并在 300 毫秒内执行的最终版本):
char[] chars = all.ToCharArray();
var iterations = 1000000;
char[] results = new char[iterations * (ReadLength + 1)];
GetRandomStrings(len, iterations, ReadLength, chars, results, 0);
string s = new string(results);
private static void GetRandomStrings(int len, int iterations, int ReadLength, char[] chars, char[] result, int resultIndex)
{
Random random = new Random();
int i = 0, index = resultIndex;
while (i < iterations && len - 100 > 0) //len is 3000000
{
var i1 = len - ReadLength;
int randomPos = random.Next() % i1;
Array.Copy(chars, randomPos, result, index, ReadLength);
index += ReadLength;
result[index] = Environment.NewLine[0];
index++;
i++;
}
}