Why can OCaml generate efficient machine code for pattern matching and not for if-else tests?
I was reading Real World OCaml and I came across this section where they compared the performance of pattern matching to the performance of if-else tests. It turned out that pattern matching in their example was significantly faster than if-else tests. Even though the code doesn't utilize any special pattern match cases that would not be possible with if-else tests, it just compares integers.
They ascribe compiler optimization for pattern matching as the reason for the performance difference. The compiler would be able to generate machine code that jumps directly ot the matched case based on an efficiently chosen set of runtime checks.
I understand this, but I don't really see why the compiler isn't able to do the same thing for the if-else tests. After all, the code is just comparing integers to integers. Is this because OCaml hasn't (yet) optimized if-else tests, or is it because it's impossible to optimize if-else tests like it's possible with pattern matching?
The pattern matching code looks like this:
let plus_one_match x = match x with | 0 -> 1 | 1 -> 2 | 2 -> 3 | _ -> x + 1 The if-else code looks like this:
let plus_one_if x = if x = 0 then 1 else if x = 1 then 2 else if x = 2 then 3 else x + 1