代码之家  ›  专栏  ›  技术社区  ›  user9193072

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

  •  0
  • user9193072  · 技术社区  · 8 年前

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

    但是,老实说,如果最终做出相同的呼吁,我无法理解他们之间的区别。 我错过什么了吗?

    第一个显式调用示例:

    #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;;
    
    1 回复  |  直到 8 年前
        1
  •  6
  •   Étienne Millon    8 年前

    关键是ocaml编译器不知道 max xs 最大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
    
    推荐文章