Running each function 1000 times show sum0 is allocating 6 words on each call.
open Printf ;;
(* Allocates
*)
let sum0 a =
let len = Array.length a in
let rec loop ofs sum =
if ofs < len then (
loop (succ ofs) (sum + a.(ofs))
) else (
sum
)
in
loop 0 0
;;
let rec sum1_help a len ofs sum =
if ofs < len then (
sum1_help a len (succ ofs) (sum + a.(ofs))
) else (
sum
)
;;
(* Does not allocate
*)
let sum1 a =
let len = Array.length a in
sum1_help a len 0 0
;;
let test which sum =
let a = Array.make 123 123 in
let minor0 = (Gc.stat ()).Gc.minor_words in
for ofs = 0 to 1000 do
ignore (sum a)
done ;
let minor1 = (Gc.stat ()).Gc.minor_words in
printf "%s:%.0f\n" which (minor1 -. minor0) ;
;;
let _ =
test "sum0" sum0 ;
test "sum1" sum1 ;
;;