【发布时间】:2012-05-24 20:34:48
【问题描述】:
我正在使用 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;
}
您对这些操作有何建议?
【问题讨论】:
-
所以你想加密一个文本文件?
-
为什么要调用 ConvertFromUtf32?我的意思是,这不像您首先调用 ConvertToUtf32 。这样一个人也可以去。
-
为什么还要浏览文本?只是 XOR 字节?
-
您的字符串只有 2 MB 大小。这绝不会占用 3 GB 的 RAM。并且做得对,这应该只需要几秒钟。还有一些事情你没有告诉我们。
标签: c# string performance optimization