Skip to content

Instantly share code, notes, and snippets.

@bluddy
Last active November 1, 2016 12:39
Show Gist options
  • Save bluddy/ca41b98f99b330bc541c4f601bc88837 to your computer and use it in GitHub Desktop.
Save bluddy/ca41b98f99b330bc541c4f601bc88837 to your computer and use it in GitHub Desktop.
Comparison of performance of filter on list/array
let filter_a f a =
if a = [| |] then [| |] else
let init = Array.unsafe_get a 0 in
let rec loop n i =
if i < Array.length a then
let x = Array.unsafe_get a i in
if f x then begin
let res = loop (n + 1) (i + 1) in
Array.unsafe_set res n x;
res
end else
loop n (i + 1)
else
Array.make n init
in
loop 0 0
let filter_l f l =
let rec loop = function
| x::xs when f x -> x::loop xs
| _::xs -> loop xs
| [] -> []
in
loop l
let big_l n =
let rec loop i =
if i = n then []
else i::loop (i+1)
in loop 1
let big_a n = Array.of_list @@ big_l n
let get_time f =
let t = Sys.time () in
let x = f () in
let t2 = Sys.time () in
x, t2 -. t
let () =
let n = int_of_string @@ Sys.argv.(1) in
Printf.printf "%d\n" n;
let big_l = big_l n in
let big_a = big_a n in
let filter_l, t_l = get_time (fun () -> filter_l (fun x -> x mod 2 = 0) big_l) in
let filter_a, t_a = get_time (fun () -> filter_a (fun x -> x mod 2 = 0) big_a) in
Printf.printf "List time %f\nArray time %f\n" t_l t_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment