Is StreamReader.Readline() really the fastest method to count lines in a file?

前端 未结 7 1249
逝去的感伤
逝去的感伤 2020-12-30 06:23

While looking around for a while I found quite a few discussions on how to figure out the number of lines in a file.

For example these three:
c# how do I count l

7条回答
  •  我在风中等你
    2020-12-30 07:00

    I tried multiple methods and tested their performance:

    The one that reads a single byte is about 50% slower than the other methods. The other methods all return around the same amount of time. You could try creating threads and doing this asynchronously, so while you are waiting for a read you can start processing a previous read. That sounds like a headache to me.

    I would go with the one liner: File.ReadLines(filePath).Count(); it performs as well as the other methods I tested.

            private static int countFileLines(string filePath)
            {
                using (StreamReader r = new StreamReader(filePath))
                {
                    int i = 0;
                    while (r.ReadLine() != null)
                    {
                        i++;
                    }
                    return i;
                }
            }
    
            private static int countFileLines2(string filePath)
            {
                using (Stream s = new FileStream(filePath, FileMode.Open))
                {
                    int i = 0;
                    int b;
    
                    b = s.ReadByte();
                    while (b >= 0)
                    {
                        if (b == 10)
                        {
                            i++;
                        }
                        b = s.ReadByte();
                    }
                    return i + 1;
                }
            }
    
            private static int countFileLines3(string filePath)
            {
                using (Stream s = new FileStream(filePath, FileMode.Open))
                {
                    int i = 0;
                    byte[] b = new byte[bufferSize];
                    int n = 0;
    
                    n = s.Read(b, 0, bufferSize);
                    while (n > 0)
                    {
                        i += countByteLines(b, n);
                        n = s.Read(b, 0, bufferSize);
                    }
                    return i + 1;
                }
            }
    
            private static int countByteLines(byte[] b, int n)
            {
                int i = 0;
                for (int j = 0; j < n; j++)
                {
                    if (b[j] == 10)
                    {
                        i++;
                    }
                }
    
                return i;
            }
    
            private static int countFileLines4(string filePath)
            {
                return File.ReadLines(filePath).Count();
            }
    

提交回复
热议问题