2010-11-02 70 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調用更快。

相關問題