当我测量程序的执行时间Hashtbl.find比没有程序慢16倍。这是为什么?
请注意,无论是否使用查找表(Map或Object),Node中的等效代码都不会显示出太多差异(仅慢3倍)
OCaml代码:
let fib =
let table = Hashtbl.create 1000 in
let rec f n =
try Hashtbl.find table n
with Not_found -> (
match n with
| 0 -> 0
| 1 -> 1
| n ->
let r = f (n - 1) + f (n - 2) in
(* Hashtbl.add table n r ; *)
r
)
in
f
Run Code Online (Sandbox Code Playgroud)
该Hashtbl.add是故意评论,我在他的Hashtable的性能成本只是有兴趣find。
ocaml ×1