gpt4 book ai didi

c# - 提高 BinaryReader 的性能

转载 作者:行者123 更新时间:2023-11-30 15:06:27 29 4
gpt4 key购买 nike

我目前正在编写一个缓存 BaseStream.PositionBaseStream.Length 属性的 BinaryReader。这是我目前所拥有的:

public class FastBinaryReader
{
BinaryReader reader;

public long Length { get; private set; }
public long Position { get; private set; }

public FastBinaryReader(Stream stream)
{
reader = new BinaryReader(stream);
Length = stream.Length;
Position = 0;
}

public void Seek(long newPosition)
{
reader.BaseStream.Position = newPosition;
Position = newPosition;
}

public byte[] ReadBytes(int count)
{
if (Position + count >= Length)
Position = Length;
else
Position += count;

return reader.ReadBytes(count);
}

public void Close()
{
reader.Close();
}
}

我不想提供 LengthPosition 属性,而是想创建一个 BaseStream 属性来公开我的 PositionLength 属性为 FastBinaryReader.BaseStream.PositionFastBinaryReader.BaseStream.Length,这样我现有的代码将保持兼容使用原始的 BinaryReader 类。

我该怎么做?

最佳答案

这是最终实现,如果有人感兴趣的话。将其作为 Stream 对象传递给 BinaryReader,而不是通常的 FileStream 对象,我的机器速度提高了大约 45%,读取 1000 字节 block 时。

请注意,Length 参数仅在读取 时准确,因为 Length 是在开始时读取的并且不会更改。如果您正在编写,它不会随着基础流的长度变化而更新。

public class FastFileStream : FileStream
{
private long _position;
private long _length;

public FastFileStream(string path, FileMode fileMode) : base(path, fileMode)
{
_position = base.Position;
_length = base.Length;
}

public override long Length
{
get { return _length; }
}

public override long Position
{
get { return _position; }
set
{
base.Position = value;
_position = value;
}
}

public override long Seek(long offset, SeekOrigin seekOrigin)
{
switch (seekOrigin)
{
case SeekOrigin.Begin:
_position = offset;
break;
case SeekOrigin.Current:
_position += offset;
break;
case SeekOrigin.End:
_position = Length + offset;
break;
}
return base.Seek(offset, seekOrigin);
}

public override int Read(byte[] array, int offset, int count)
{
_position += count;
return base.Read(array, offset, count);
}

public override int ReadByte()
{
_position += 1;
return base.ReadByte();
}
}

关于c# - 提高 BinaryReader 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7824255/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com