同一个函数的执行是否比将结果关联到一个变量差两倍?

is the execution of the same function twice worse than associating the result to a variable?

有人告诉我,就性能而言,第一段代码比第二段差。

但是,老实说,如果最终发出相同的调用,我无法弄清楚它们有何不同。 我错过了什么吗?

带有显式调用的第一个示例:

#let rec max l =
match l with
x::[]->x
| x::xs -> if(x > max xs) 
     then x else max xs;;

使用变量的第二个例子:

#let rec max l =
match l with
x::[]->x
| x::xs -> let m = max xs
in
if (x>m) then x else m;;

关键是 ocaml 编译器不知道 max xsmax xs 是一回事,所以你的第一个例子相当于:

let rec max l =
  match l with
   | x::[]-> x
   | x::xs ->
     let m1 = max xs in (* first call *)
     if (x > m1) then
       x
     else
       let m2 = max xs in
       m2 (* second call *)
;;

只进行一次调用是有效的优化,但在一般情况下是不正确的。例如:

let f () =
  print_endline "hello";
  print_endline "hello";
  3

不等同于:

let g () =
  let x = print_endline "hello" in
  x;
  x;
  3