多个BinaryReader.Read()和BinaryReader.ReadBytes(int i)之间的区别

时间:2010-11-02 15:02:02

标签: c# binary

我正在搜索BinaryReader.Skip函数,而我遇到了这个feature request on msdn。 他说你可以使用它来提供你自己的BinaryReader.Skip()函数。

只看这段代码,我想知道为什么他选择这种方式跳过一定数量的字节:

    for (int i = 0, i < count; i++) {
        reader.ReadByte();
    }

它和之间是否有区别:

reader.ReadBytes(count);

即使只是一个小的优化,我也不愿意。因为现在它对我来说没有意义,为什么你会使用for循环。

public void Skip(this BinaryReader reader, int count) {
    if (reader.BaseStream.CanSeek) { 
        reader.BaseStream.Seek(count, SeekOffset.Current); 
    }
    else {
        for (int i = 0, i < count; i++) {
            reader.ReadByte();
        }
    }
}

4 个答案:

答案 0 :(得分:2)

不,没有区别。 编辑:假设流有足够的字节

ReadByte方法只是转发到基础Stream的ReadByte方法。

ReadBytes方法调用基础流的Read,直到它读取所需的字节数。
它的定义如下:

public virtual byte[] ReadBytes(int count) {
    if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); 
    Contract.Ensures(Contract.Result<byte[]>() != null); 
    Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
    Contract.EndContractBlock(); 
    if (m_stream==null) __Error.FileNotOpen();

    byte[] result = new byte[count];

    int numRead = 0;
    do { 
        int n = m_stream.Read(result, numRead, count); 
        if (n == 0)
            break; 
        numRead += n;
        count -= n;
    } while (count > 0);

    if (numRead != result.Length) {
        // Trim array.  This should happen on EOF & possibly net streams. 
        byte[] copy = new byte[numRead]; 
        Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
        result = copy; 
    }

    return result;
} 

对于大多数流,ReadBytes可能会更快。

答案 1 :(得分:2)

如果到达流的末尾,

ReadByte将抛出EndOfStreamException,而ReadBytes则不会。这取决于你是否希望Skip抛出,如果它不能跳过请求的字节数而不到达流的末尾。

答案 2 :(得分:1)

ReadBytes比多个ReadByte调用快。

答案 3 :(得分:0)

它是一个非常小的优化,它偶尔会跳过字节(而不是将它们读入ReadByte)想象一下

if(vowel)
{
    println(vowel);
}
else
{
nextLetter();
}

如果可以阻止额外的函数调用,则可以节省一点运行时间

相关问题