Home > front end >  Is there a performance cost of `Option.bind` compared to pattern matching?
Is there a performance cost of `Option.bind` compared to pattern matching?

Time:10-13

I saw some OCaml code like this (reduced example):

match x_opt with
| Some x ->
  (match do_some_stuff_with_x... with
   | Some y -> do_some_stuff_with_y...
   | None -> None
   )
| None -> None

Are there high performance costs to the following alternative? (in particular, memory usage from the closures)?

(* using core_kernel's Option module *)
x_opt
|> Option.bind ~f:(fun x -> do_some_stuff_with_x....)
|> Option.bind ~f:(fun y -> do_some_stuff_with_y....)

Possible answers:

  • The Option.bind version can be arbitrarily costly, depending on what you close over
  • flambda is usually smart enough to optimize away the closures (like rustc does)
  • other

CodePudding user response:

The bind version might have a small overhead of creating a closure, which is usually, indeed, optimized away by flambda. Even if the closure is not created, e.g., when the bound function doesn't capture anything from the outside context, like in Option.bind ~f:Option.return, there is a minuscule overhead of an extra call.

All these overheads could be considered negligible unless they are run in a very hot loop. So unless you profiled and found out that it is an issue, try using the style that you find the most readable in the given situation.

  • Related