Thanks for trying, could you at least humour the following to get around the re-creation???
using (System.IO.FileStream fs = new System.IO.FileStream(@"c:\file.txt", System.IO.FileMode.Open ,System.IO.FileAccess.Read))
using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
{
for (Int32 i = 0; i < 100; i++)
{
long count = 0;
Not only is this about strings rather than files, but it is very, very difficult to measure the actual time taken by a StreamReader method. Becasue StreamReader does not have a Seek or Rewind method, you have to construct a new instance each time round the loop, and this affects the timings (it adds code that isn't necessary for the others but which not does not bear directly on the counting task). However, I did try it:
ssr.Start();
for (int i = 0; i < 100; i++)
{
StreamReader sr = new StreamReader(@"D:\Temp\MyLargeTextFile.txt");
index = LinesCountStream(sr);
sr.Dispose();
}
ssr.Stop();
...
static long LinesCountStream(StreamReader sr)
{
long count = 0;
while (sr.ReadLine() != null)
{
count++;
}
return count;
}
Interestingly, it works out at about 925 milliseconds, compared to 165 for the BF+I version. I suspect that the time is mostly to do with the allocation of each line to a separate string, which is a necessary part of the StreamReader.ReadLine method.
Thank you for pointing that out - with capitals. Whilst I understand the difference, I merely (perhaps wrongly) assumed from the comment above - "The input file is 1.64Mb, and contains around 23K lines." - that the whole process was because a file had been read in and we wanted the quickest way to count the lines.
Sure, if the string is drawn from say a database, then my alternative doesn't apply. Perhaps I read it wrong?
EDIT - My apologies - another comment hidden away stated that this was just for testing and I missed it!
Last Visit: 31-Dec-99 18:00 Last Update: 23-Sep-24 18:07