Reputation: 78
When using pattern matching with Ocaml, I sometimes hesitate to use the wildcard (_
) and instead use a variable that I can name for clarity. I was wondering if it's (although slightly I presume) less efficient than using it, because using the wildcard the compiler knows the value won't be reachable, and no pointer is created.
Consider the three functions below:
No 1
let compare = function
[], [] -> true
|h::t, h2::t2 when h > h2 -> compare t t2
|h::t, h2::t2 -> false
No 2
let compare = function
[], [] -> true
|h::t, h2::t2 when h > h2 -> compare t t2
|_::_, _::_ -> false
No 3
let compare = function
[], [] -> true
|h::t, h2::t2 when h > h2 -> compare t t2
|_ -> false
No3 should be faster, but is 2faster and/or use less memory than the first one? I dogged into the caml documentation and couldn't find information on the wildcard implementation.
Upvotes: 0
Views: 1755
Reputation: 1263
The compiler does not really care whether unused variables appear in patterns or not. However, it does care which branches are present and their order.
For example, your first two examples use non-exhaustive pattern matching, so the compilers will add some extra branches that raise an exception at runtime. Obviously, these branches increase the size of the executable.
Even if your pattern matching is exhaustive, there might still be a difference. In your third example, your catch-all branch causes the compiler to create all the underlying cases and to make them jump to this common code. If you had explicitly written all the branches, then each case would have been responsible to returning its own result.
So, depending on whether the compiler decides to perform jump/epilogue threading and block tail merging, your code might be more or less large, more or less fast. That said, there should be no difference on the memory consumption. But even that is not guaranteed, because code changes might in turn cause the inlining heuristics to diverge, and thus increase or decrease optimization opportunities.
To summarize, short of looking at the generated assembly code, it is hard to predict the decisions of the compiler, even on such simple functions.
Upvotes: 2