Bill Pierce wrote:
Is it faster to read through a file, without checking for end of
stream, and catch the EndOfStreamExce ption or to do a check for
position vs. length after reading each line of a file? This is using a
BinaryReader.
I am going to setup a some performance tests but wanted to gather any
input from the learned groopies.
Results of my testing didn't seem very conclusive. I might have gone
about it the wrong way but anyways...
All depends on how many reads you do to the file. It appears that
<5000 reads, it is faster to check position/length. >5000 reads, it is
faster to catch the EndOfStream exception
Here is the code I used for the tests, using files of varying length,
averaging multiple reads of the file. The file being read is just a
bunch of sequential uints written using a binary reader.
private static double ReadWithPositio nCheck(string fileName)
{
long start = 0, end = 0;
using(Stream stream = File.Open(fileN ame, FileMode.Open,
FileAccess.Read , FileShare.Read) )
{
using(BinaryRea der reader = new BinaryReader(st ream))
{
QueryPerformanc eCounter(out start);
long length = reader.BaseStre am.Length;
long readLength = length - 4;
long position = 0;
while(position < readLength)
{
reader.ReadUInt 32();
position += 4;
}
QueryPerformanc eCounter(out end);
}
}
return (double)(end - start) / Frequency;
}
private static double ReadWithoutPosi tionCheck(strin g fileName)
{
long start = 0, end = 0;
using(Stream stream = File.Open(fileN ame, FileMode.Open,
FileAccess.Read , FileShare.Read) )
{
using(BinaryRea der reader = new BinaryReader(st ream))
{
QueryPerformanc eCounter(out start);
try
{
while(true)
{
reader.ReadUInt 32();
}
}
catch(EndOfStre amException)
{
}
QueryPerformanc eCounter(out end);
}
}
return (double)(end - start) / Frequency;
}