Reputation: 27
For my project I need to write UInt16, UInt32, Bytes and Strings from a file. I started with a simple class I wrote like this:
public FileReader(string path) //constructor
{
if (!System.IO.File.Exists(path))
throw new Exception("FileReader::File not found.");
m_byteFile = System.IO.File.ReadAllBytes(path);
m_readPos = 0;
}
public UInt16 getU16() // basic function for reading
{
if (m_readPos + 1 >= m_byteFile.Length)
return 0;
UInt16 ret = (UInt16)((m_byteFile[m_readPos + 0])
+ (m_byteFile[m_readPos + 1] << 8));
m_readPos += 2;
return ret;
}
I thought it might be better to use the already existing BinaryReader though and so I tried it, but I noticed that it is slower than my approach. Can somebody explain why this is and if there is another already existing class I could use to load a file and read from it?
~Adura
Upvotes: 0
Views: 2417
Reputation: 140228
You have all the data upfront in an array in memory whereas BinaryReader
streams the bytes in one at a time from the source which I guess is a file on disk. I guess you could speed it up by passing it a stream that reads from an in-memory array:
Stream stream = new MemoryStream(byteArray);
//Pass the stream to BinaryReader
Note that with this approach you need to fill the entire file in memory at once but I guess that's ok for you.
Upvotes: 1