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

Tim*_*sen 5 c# binary

我正在搜索BinaryReader.Skip函数,而我在msdn上遇到了这个功能请求.他说你可以使用它来提供你自己的BinaryReader.Skip()函数.

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

    for (int i = 0, i < count; i++) {
        reader.ReadByte();
    }
Run Code Online (Sandbox Code Playgroud)

它和之间有区别吗:

reader.ReadBytes(count);
Run Code Online (Sandbox Code Playgroud)

即使它只是一个小的优化,我也不愿意.因为现在它对我来说没有意义,为什么你会使用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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 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;
} 
Run Code Online (Sandbox Code Playgroud)

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

  • 但这对我来说没有任何意义。为什么 ReadBytes 会更快? (2认同)
  • @Timo,如果字节数足够大,您将获得块内存副本和更少的总方法调用。ReadByte 是虚拟的,这会增加少量的开销。无论哪种方式,都不可能产生巨大的差异。 (2认同)
  • @Dan,@Timo:它将向底层流发出更少的请求。从磁盘读取时,这可能会产生影响。 (2认同)