简体   繁体   English

如何使循环更快

[英]How To Make This For Loop Faster

I have the problem that this for loop takes so much time to complete. 我的问题是,此for循环需要太多时间才能完成。 I want a faster way to complete it. 我想要一个更快的方法来完成它。

ArrayList arrayList = new ArrayList();
byte[] encryptedBytes = null;
for (int i = 0; i < iterations; i++)
{
    encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i,
                     base64BlockSize));
    arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true));
}

The iterations variable sometimes is larger than 100,000 and that takes like for ever. iterations变量有时大于100,000,这就像永远一样。

Did you consider running the decryption process in a parallel loop. 您是否考虑过在并行循环中运行解密过程。 Your input strings have to be prepared first in a regular loop, but that's a quick process. 您必须首先在常规循环中准备输入字符串,但这是一个快速的过程。 Then you run the decryption in Parallel.For : 然后在Parallel.For运行解密:

var inputs = new List<string>();
var result = new string[(inputString.Length / 64) - 1];

// Create inputs from the input string.
for (int i = 0; i < iterations; ++i)
{
    inputs.Add(inputString.Substring(base64BlockSize * i, base64BlockSize));
}

Parallel.For(0, iterations, i =>
{
    var encryptedBytes = Convert.FromBase64String(inputs[i]);
    result[i] = rsaCryptoServiceProvider.Decrypt(encryptedBytes, true);
});

I assumed the result returned is a string but if that's not the case then you have to adjust the type for the concurrent bag collection. 我假设返回的结果是一个字符串,但是如果不是这样,则必须调整并发bag集合的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM