liptolip
liptolip

Reputation: 7

working with large string

I am working with a large string in C#. For example, my string length is 2.000.000 characters. I have to encrypt this string. I have to save it as a text file on a hard disk. I've tried to encrypt by using XOR for the fastest and basic text encryption but still takes too long encryption. It takes 1 hour with 2.13 GHz duo cpu and 3 GB RAM. Also, saving the file (using StreamWriter Write method) and reading from the file (using StreamReader ReadToEnd method) takes too long.

The code:

public static string XorText(string text) 
{   
   string newText = ""; 
   int key = 1; 
   int charValue; 
   for (int i = 0; i < text.Length; i++) 
   {
     charValue = Convert.ToInt32(text[i]); //get the ASCII value of the character 
     charValue ^= key; //xor the value 
     newText += char.ConvertFromUtf32(charValue); //convert back to string 
   } 
   return newText; 
}

What is your advice for these operations?

Upvotes: 0

Views: 3476

Answers (1)

Saeed Amiri
Saeed Amiri

Reputation: 22565

I would suggest use StringBuilder instead of string for large strings, also is better to show your code to see if any other optimization is possible. e.g for reading/writing from/into files you can use buffers.

Update: As I can see in your code biggest problem (with this code) is in this line:

newText += char.ConvertFromUtf32(charValue);

String is immutable object, and by += operator every time you will create a new instance of newText and when the length is big this causes to time and memory problems, so instead of string if you use StringBuilder this line of code will be as this:

newText.Append(char.ConvertFromUtf32(charValue));

and this function will be run extremely faster.

Upvotes: 4

Related Questions