问题描述
我正在使用 BinaryReader 读取文件并由新行 \n
拆分为 ReadOnlySpan<byte>
(添加上下文我想要字节而不是字符串,因为我正在使用 Utf8JsonReader
并尝试避免从字符串复制到字节数组)。
故意使用大缓冲区是有原因的 - 16kB 对应用程序来说是可以的,并且一次处理一个缓冲区。
然而,与 File.ReadAllBytes(filename)
在 1 秒内完成相比,下面的代码在同一台机器上需要 30+ 秒。
我天真地假设 BinaryReader
会提前阅读并提前缓存 - 似乎不是这种情况,或者至少没有为此使用任何标志(我似乎无法罚款)。
我怎样才能提高我的表现,或者通过一个替代类来实现行拆分?
static void Main(string[] args)
{
using var fileStream = File.Open(args[0],FileMode.Open);
using (var reader = new BinaryReader(fileStream))
{
var i = 0;
ReadOnlySpan<byte> line = null;
while ((line = reader.ReadLine()) != null)
{
// Process the line here,one at a time.
i++;
}
Console.WriteLine("Read line " + i);
}
}
public static class BinaryReaderExtensions
{
public static ReadOnlySpan<byte> ReadLine(this BinaryReader reader)
{
if (reader.IsEndOfStream())
return null;
// Buffer size is deliberate,we process one line at a time.
var buffer = new byte[16384];
var i = 0;
while (!reader.IsEndOfStream() && i < buffer.Length)
{
if((buffer[i] = reader.ReadByte()) == '\n')
return new ReadOnlySpan<byte>(buffer,i + 1);
i++;
}
return null;
}
public static bool IsEndOfStream(this BinaryReader reader)
{
return reader.BaseStream.Position == reader.BaseStream.Length;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)