Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between multiple BinaryReader.Read() and BinaryReader.ReadBytes(int i)

Tags:

c#

binary

I was searching for a BinaryReader.Skip function, while I came across this feature request on msdn. He said you can provide your own BinaryReader.Skip() function, by using this.

Only looking at this code, I'm wondering why he chose this way to skip a certain amount of bytes:

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

Is there a difference between that and:

reader.ReadBytes(count);

Even if it's just a small optimalisation, I'd like to undestand. Because now it doesnt make sense to me why you would use the for loop.

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();
        }
    }
}
like image 453
Timo Willemsen Avatar asked Nov 02 '10 15:11

Timo Willemsen


1 Answers

No, there is no difference. EDIT: Assuming that the stream has enough byes

The ReadByte method simply forwards to the underlying Stream's ReadByte method.

The ReadBytes method calls the underlying stream's Read until it reads the required number of bytes.
It's defined like this:

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;
} 

For most streams, ReadBytes will probably be faster.

like image 172
SLaks Avatar answered Sep 28 '22 06:09

SLaks