Kartik
Kartik

Reputation: 1506

Suggestion to improve performance of a piece of c# code

We are developing a highly realtime application. The application isn't performing up to the mark. We did some performance profiling and found following piece of code takes most of the time

for (int i = 0; i < _chunkSize; i++)
{
   outputData[i] = (byte)(inputText[i] ^ nonce[i % NonceSize]);
}

Where _chunkSize is 1024000 and NonceSize is 16. The variables inputText, outputData and nonce are byte arrays.

Please suggest changes to this snippet to improve performance

EDit

To give more context -

I have a developed my own DRM system where I use a custom .NET implementation of CTR encryption algorithm. While the movie is being played, 1 MB chunks of the movie are read from a encrypted media file, decrypted in memory and fed to the player. The decryption runs slowly and hence the player fails to play the movie of larger size (>300MB). The nonce in the above piece of code is calculated at runtime for every encrypted 1 MB chunk and XORed with the chunk to decrypt it.

Upvotes: 0

Views: 112

Answers (1)

dcastro
dcastro

Reputation: 68670

You can avoid using the remainder operator to keep the index in the [0, NonceSize[ range, and do that manually instead.

int index = 0;
for (int i = index; i < _chunkSize; i++, index++)
{
    if(index == NonceSize)
        index = 0;
    outputData[i] = (byte)(inputText[i] ^ nonce[index]);
}

That might help a bit.


I increased the _chunkSize to 102400000, to make the results more relevant.

With the remainder operator

1431 1411 1445 1368 1312 1427 1436 1265 1102 1077
Average: 1327.4

Without

1133 1197 1122 973 976 1032 1460 1229 1211 1145
Average: 1147.8

Without the remainder operator, the loop was 13.6% faster.

Upvotes: 3

Related Questions