Version franÁaise
Home ††† About ††† Download ††† Resources ††† Contact us †††
Browse thread
best and fastest way to read lines from a file?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Mattias Engdegå rd <mattias@v...>
Subject: Re: [Caml-list] best and fastest way to read lines from a file?
>let line_count filename =
>   let f = open_in filename in
>   let rec loop count =
>     match (readline f) with
>       | Some(_) -> loop (count+1)
>       | None -> count in
>   loop 0;;

Something like this should be even faster:

exception Done of int

let line_count file =
  let rec loop count =
    let _ =
      try
	input_line f
      with End_of_file -> raise (Done count)
    in
      loop (count + 1)
  in
    try loop 0 with Done x -> x

as it avoids unnecessary consing in the inner loop.