【发布时间】:2013-01-14 12:23:24
【问题描述】:
我需要将十六进制字符串转换为字节数组,然后将其写入文件。下面的代码给出了 3 秒 的延迟。 hex下面是一个长度为1600的十六进制字符串。有没有其他方法可以加快速度?
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 5000; i++)
{
FileStream objFileStream = new FileStream("E://CRec Correcting Copy//Reader//bin//Debug//Files//Raw Data//a123.txt", FileMode.Append, FileAccess.Write);
objFileStream.Seek(0, SeekOrigin.End);
objFileStream.Write(stringTobyte(hex), 0, stringTobyte(hex).Length);
objFileStream.Close();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
stringTobyte 是一种将十六进制字符串转换为字节数组的方法。
public static byte[] stringTobyte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}
}
请告诉我延迟发生在哪里?
【问题讨论】:
-
为什么要创建/打开/搜索/写入/关闭 5,000 次?什么可能会让某人认为这是明智的?这就像开车去商店 50 次才能得到 50 个苹果!随心所欲地打开、搜索、写入,然后关闭。
-
只打开一次流,写入几KB的块而不是一个字节。
-
请告诉我,这段代码是故意创建的,作为糟糕代码的示例或“优化这段代码”练习。
-
十六进制总是空的吗? 5000 循环可能与时间有关……您几乎可以立即将 1600 字节的数据放入文件中。所以你的代码肯定有问题。最有可能与循环有关。
-
为什么需要stringTobyte,什么时候System.Encoding.Ascii.getbytes()会做你想做的事
标签: c# hex byte filestream