当我遇到这个feature request on msdn时,我正在搜索一个BinaryReader.Skip函数。他说你可以通过使用这个来提供你自己的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();
}
}
}发布于 2010-11-02 23:04:27
不,没有区别。编辑:假设流有足够的byes
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可能会更快。
发布于 2010-11-02 23:06:39
如果到达流的末尾,ReadByte将抛出EndOfStreamException,而ReadBytes不会。这取决于您是否希望Skip在未到达流的末尾时跳过请求的字节数而抛出。
发布于 2010-11-02 23:18:05
ReadBytes比多个ReadByte调用更快。
https://stackoverflow.com/questions/4078936
复制相似问题