简体   繁体   中英

How To Make This For Loop Faster

I have the problem that this for loop takes so much time to complete. 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.

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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