Counting lines in a file

J

jabailo

Which would be faster for counting lines in a StreamReader:

(a) iterate through a file using .ReadLine() and adding to a counter, i++

(b) doing a .ReadToEnd() and then using an IndexOf() method to count the
occurances of \r\n

(c) doing a .ReadToEnd() and using a RegEx to count the number of occurances
of \r\n
 
W

wbekker

Hi Javailo,

I would guess that option c scales better, but a small test might show
the real winner ;-)

Ward
 
D

Dmytro Lapshyn [MVP]

Hi,

I think (b) should be the fastest, but I wouldn't expect any significant
difference between (a) and (b) since Windows does efficient disk read
buffering behind the scenes.
I think (c) should be the slowest because of RegExp.

Anyway, it's all just guessing, why don't you try all the three approaches
and post the real result here? ;-)
 
C

Chad Z. Hower aka Kudzu

Which would be faster for counting lines in a StreamReader:

The only way to find out is to test it, and in fact different ones may be faster depending on size and
characteristics of the file.
(a) iterate through a file using .ReadLine() and adding to a counter,
i++

This is probably the best over all considering memory considerations etc if your file is large. And
probably the fastest too.
(b) doing a .ReadToEnd() and then using an IndexOf() method to count
the occurances of \r\n

(c) doing a .ReadToEnd() and using a RegEx to count the number of
occurances of \r\n

Both of these will consume large amoutns of memory if the file is large.


--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Develop ASP.NET applications easier and in less time:
http://www.atozed.com/IntraWeb/
 
I

Ignacio Machin \( .NET/ C# MVP \)

hi,

the first option is the way to go, unless you are 100% sure that the size of
the file in advance.

The others solutions are not portable, you should use
Environment.NewLine() instead of "\r\n"

cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top