Golang: How do I determine the number of lines in a file efficiently?

后端 未结 3 667
我寻月下人不归
我寻月下人不归 2020-12-04 13:29

In Golang, I am looking for an efficient way to determine the number of lines a file has.

Of course, I can always loop through the entire file, but does not seem ver

3条回答
  •  盖世英雄少女心
    2020-12-04 14:08

    Here's a faster line counter using bytes.Count to find the newline characters.

    It's faster because it takes away all the extra logic and buffering required to return whole lines, and takes advantage of some assembly optimized functions offered by the bytes package to search characters in a byte slice.

    Larger buffers also help here, especially with larger files. On my system, with the file I used for testing, a 32k buffer was fastest.

    func lineCounter(r io.Reader) (int, error) {
        buf := make([]byte, 32*1024)
        count := 0
        lineSep := []byte{'\n'}
    
        for {
            c, err := r.Read(buf)
            count += bytes.Count(buf[:c], lineSep)
    
            switch {
            case err == io.EOF:
                return count, nil
    
            case err != nil:
                return count, err
            }
        }
    }
    

    and the benchmark output:

    BenchmarkBuffioScan   500      6408963 ns/op     4208 B/op    2 allocs/op
    BenchmarkBytesCount   500      4323397 ns/op     8200 B/op    1 allocs/op
    BenchmarkBytes32k     500      3650818 ns/op     65545 B/op   1 allocs/op
    

提交回复
热议问题