使用大字符串
本文关键字:字符串 | 更新日期: 2023-09-27 18:34:22
我正在C#中使用一个大字符串。例如,我的字符串长度为 2.000.000 个字符。我必须加密这个字符串。我必须将其另存为硬盘上的文本文件。我尝试使用 XOR 进行加密,以实现最快和基本的文本加密,但加密时间仍然太长。使用 2.13 GHz 双 CPU 和 3 GB RAM 需要 1 小时。此外,保存文件(使用 StreamWriter Write 方法)和从文件读取(使用 StreamReader ReadToEnd 方法)需要很长时间。
代码:
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;
}
您对这些操作有什么建议?
我建议对大字符串使用 StringBuilder
而不是字符串,也最好显示您的代码以查看是否可以进行任何其他优化。 例如,对于从/写入文件,您可以使用缓冲区。
更新:正如我在您的代码中看到的那样,最大的问题(使用此代码)位于以下行:
newText += char.ConvertFromUtf32(charValue);
String
是不可变的对象,并且通过运算符+=
每次您都会创建一个新的newText
实例并且当长度很大时,这会导致时间和内存问题,因此如果您使用StringBuilder
,则不会string
,则此行代码将如下所示:
newText.Append(char.ConvertFromUtf32(charValue));
并且此功能的运行速度将非常快。