let distance (a1 : int array) (a2 : int array) =
let open Array in
let len = length a1 in
let acc = ref 0 in
for i = 0 to len - 1 do
let v1 = unsafe_get a1 i in
let v2 = unsafe_get a2 i in
let d = v1 - v2 in
acc := !acc + d * d
done;
!acc
the OCaml goes 3 times faster. This is what would be produced if OCaml's inliner had triggered on the original definition of `distance`, so that is probably the main difference in the two language's performance. If you inline some of the other functions by hand (and tidy up some of the sillier parts of the OCaml code) it easily runs 4 times faster than the original.