Skip to content

Instantly share code, notes, and snippets.

@JekRock
Created May 4, 2023 08:35
Show Gist options
  • Save JekRock/dc924bfa820848f75c27a6952dc18ce4 to your computer and use it in GitHub Desktop.
Save JekRock/dc924bfa820848f75c27a6952dc18ce4 to your computer and use it in GitHub Desktop.
Fast line counter in Go
// source https://stackoverflow.com/questions/24562942/golang-how-do-i-determine-the-number-of-lines-in-a-file-efficiently
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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment