我有这个对象:Dictionary<byte, BitArray>()
它充满了来自霍夫曼树的价值观。要将流的每个字节编码为霍夫曼二进制值,我会这样做:
// Bytes are the bytes to be encoded, encoded is the output string
foreach (byte c in Bytes)
{
encoded += _translationTable[c].ToBitsString();
}
这是扩展方法:
//Converts the bitarray in a binary string
public static string ToBitsString(this BitArray bitArr)
{
string retStr = string.Empty;
foreach (bool bit in bitArr)
{
retStr += (bit) ? "1" : "0";
}
return retStr;
}
编码64kb数据需要将近3秒钟,有没有办法以更快的方式实现这一结果?
答案 0 :(得分:7)
听起来你在循环中执行字符串连接。那是very inefficient way of building a new string。我怀疑你想要:
<blockTime><blockSequence><blockSize><block>
既然我们可以看到var builder = new StringBuilder();
foreach (byte c in Bytes)
{
builder.Append(_translationTable[c].ToBitsString());
}
var encoded = builder.ToString();
做了什么,就可以轻松地重写它以接受ToBitsString
附加到:{/ p>
StringBuilder
然后循环的主体将是:
public static void AppendBitsTo(this BitArray bitArray, StringBuilder builder)
{
foreach (bool bit in bitArray)
{
builder.Append(bit ? "1" : "0");
}
}