У меня есть спецификация двоичного файла, которая описывает структуру пакетированных данных. Каждый пакет данных имеет двухбайтовый шаблон синхронизации, поэтому возможно сканирование для начала пакета с использованием комбинаций BinaryReader
и FileStream
:
while(!reader.EndOfFile)
{
// Check for sync pattern.
if (reader.ReadUInt16() != 0xEB25)
{
// Move to next byte.
reader.BaseStream.Seek(-1, SeekOrigin.Current);
continue;
}
// If we got here, a sync pattern was found.
}
Этот процесс отлично работает в прямом направлении, но аналогичное сканирование кода в обратном направлении по меньшей мере на два порядка медленнее:
while(!reader.BeginningOfFile)
{
// Check for sync pattern.
if (reader.ReadUInt16() != 0xEB25)
{
// Move to previous byte.
reader.BaseStream.Seek(-3, SeekOrigin.Current);
continue;
}
// If we got here, a sync pattern was found.
}
Я пробовал несколько обходных решений, таких как возврат к произвольной сумме (в настоящее время 1 мегабайт) и сканирование вперёд, но становится ясно, что мне действительно нужен BinaryReader
или FileStream
, который изменен, чтобы адекватные эксплуатационные характеристики при чтении как в прямом, так и в обратном направлениях.
У меня уже есть FastFileStream
, который улучшает производительность прямого чтения путем подклассификации обычного FileStream
и кэширования свойств Position
и Length
(он также предоставляет свойства BeginningOfFile
и EndOfFile
). Это то, что управляет переменной reader
в приведенном выше коде.
Есть ли что-то подобное, что я мог бы сделать для улучшения производительности обратного чтения, возможно, включив MemoryStream
в качестве буфера?