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: Brian Hurt <bhurt@j...>
Subject: Re: [Caml-list] best and fastest way to read lines from a file?
Mattias EngdegŚrd wrote:

>>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.
>
>__
>

This should be a FAQ.

let line_count file =
    let rec loop count =
       let test =
          try
             let _ = input_line f in
             true
          with
          | Not_found -> false
       in
       if test then
          loop (count + 1)
       else
          count
    in
    loop 0
;;

No consing, no unnecessary try/catch, tail recursive.

Brian