Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
I'm reading a binary file and need too many pointer movements. And I know MS is much faster than FS. But what I'm doing is that, first I read all bytes to cache then use MS. So will it make any difference or I should directly read the file ?

something like this

byte[] data = File.ReadAllBytes(path);
MemoryStream ms = new MemoryStream(data);
BinaryReader br = new BinaryReader(ms);


or

BinaryReader br = new BinaryReader(File.OpenRead(path));




Edited :

after creating BinaryReader I have to do thousands of pointers movements like

br.BaseStream.Position = 99999;
br.BaseStream.Position = 2;
br.BaseStream.Position = 86765;
Posted
Updated 11-Feb-10 21:30pm
v2

I expect if you look into the source, that ReadAllBytes does exactly what you're doing. It's better to use the shortcut as it's neater, but that is all.
 
Share this answer
 
I guess it depends on the size of the file, and the amount of memory available. You should try profiling both approaches and see which one is faster for you.

If the file size is large and you have a small amount of memory to fit it in, getting all bytes into a byte[] and then into the memory stream is going to take up quite a bit of virtual memory, and in turn, a large number of page faults.

OTOH, using a FileStream to do random access will again lead to large number of disk accesses. But both the operating system and the FileStream class do buffering - although to what extent, I don't know.
 
Share this answer
 
Well, I go for MS...here are results


with MS

00:00:00.0014218
00:00:00.0013840
00:00:00.0014123
00:00:00.0016129
00:00:00.0018564
00:00:00.0034196
00:00:00.0015400
00:00:00.0015265
00:00:00.0016011



directly

00:00:00.0093724
00:00:00.0086874
00:00:00.0086332
00:00:00.0087101
00:00:00.0087691
00:00:00.0088588
00:00:00.0090902
00:00:00.0089308
00:00:00.0087806
00:00:00.0085874
00:00:00.0087815
00:00:00.0090007



   System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
   sw.Start();
   string path = @"D:\american.gxt";
   byte[] data = File.ReadAllBytes(path);
   MemoryStream ms = new MemoryStream(data);
   BinaryReader br = new BinaryReader(ms);
// BinaryReader br = new BinaryReader(File.OpenRead(path)); //uncomment this line for II method


   Random r = new Random();
   int length = (int)br.BaseStream.Length;

   for (int a = 0; a < 10000; a++)
   {
       br.BaseStream.Position = r.Next(0, length);
   }
   sw.Stop();

   richTextBox1.AppendText(sw.Elapsed.ToString()+"\r\n");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900