2010-11-02 43 views
5

之间的差异我正在寻找一个BinaryReader.Skip函数,当我遇到这feature request on msdn。 他说你可以通过使用这个提供你自己的BinaryReader.Skip()函数。多个BinaryReader.Read()和BinaryReader.ReadBytes(int i)

只盯着这个代码,我不知道他为什么选择这种方式来跳过一定量的字节:

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

回答

2

不,没有区别。 EDIT:假设流具有足够轮空

ReadByte方法简单地转发到基础流的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可能会更快。

+2

虽然这对我没有任何意义。为什么ReadBytes会更快? – 2010-11-02 15:11:20

+2

@Timo,如果字节数足够大,您将获得块存储器副本和更少的总方法调用。 ReadByte是虚拟的,可以添加少量的开销。这两种方式都不会有很大的差别。 – 2010-11-02 15:16:53

+2

@Dan,@Timo:它将向底层流发出较少的请求。从磁盘读取数据时,这可能会有所帮助。 – SLaks 2010-11-02 15:18:15

2

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

0

它是一个非常小的优化,这将偶尔会跳过字节(而不是读他们到ReadByte)考虑一下这种方式

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

如果你能避免额外的函数调用你节省一点运行

1

ReadBytes比多个ReadByte调用更快。

相关问题