Count the number of lines in a file without reading entire file into memory?

前端 未结 15 1434
忘掉有多难
忘掉有多难 2020-12-24 01:38

I\'m processing huge data files (millions of lines each).

Before I start processing I\'d like to get a count of the number of lines in the file, so I can then indic

15条回答
  •  情书的邮戳
    2020-12-24 02:20

    Using foreach without inject is about 3% faster than with inject. Both are very much faster (more than 100x in my experience) than using getc.

    Using foreach without inject can also be slightly simplified (relative to the snippet given elsewhere in this thread) as follows:

    count = 0;  File.foreach(path) { count+=1}
    puts "count: #{count}"
    

提交回复
热议问题